Created
September 11, 2021 16:42
-
-
Save Kinetic27/690404d3114b72b857afdd109569a4fe to your computer and use it in GitHub Desktop.
틱택토 코틀린
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Random | |
/** | |
* @author kinetic | |
*/ | |
fun main() { | |
val board = Array(9) { " " } | |
var turn = 0 // 0 is human's turn, 1 is computer's turn | |
println("Tic Tak Toe") | |
println("사람: X, 컴퓨터: O") | |
println("-".repeat(15) + "\n") | |
var n: Int? = -1 | |
/* Try to get input Start */ | |
game@ while (true) { | |
input@ while (true) { | |
when (turn) { | |
/* User Data Input Start*/ | |
0 -> { | |
print("좌표로 쓰일 정수값(0 ~ 2) 두개를 x y 순서로 입력해주세요. ex) 2 2: ") | |
// get line by user | |
val userInput = readLine()!!.split(" ").map { it.toIntOrNull() } | |
// check input is valid | |
if (userInput[0] in 0..2 && userInput[1] in 0..2) { | |
// change 2D coordinate to 1D coordinate | |
n = userInput[0]!! + userInput[1]!! * 3 | |
} else { | |
print("잘못된 입력입니다. ") | |
continue@input | |
} | |
} | |
/* User Data Input End*/ | |
// Random Computer Input | |
1 -> n = Random().nextInt(9) | |
} | |
if (board[n!!] != " ") { | |
if (turn == 0) print("이미 입력된 칸입니다, ") | |
} else break@input | |
} | |
/* Try to get input End */ | |
// Input data to board, 0 is human's turn and 1 is computer's turn | |
board[n!!] = if (turn == 0) "X" else "O" | |
/* Print Board Start */ | |
(3 downTo 1).forEach { | |
println(" ${board[it * 3 - 3]} | ${board[it * 3 - 2]} | ${board[it * 3 - 1]}") // print 1 line of board | |
if (it in 2..3) println("---|---|---") // print contour between lines | |
} | |
println("\n" + "-".repeat(15) + "\n") | |
/* Print Board End */ | |
/* Check game is over Start*/ | |
// All bingo cases | |
val bingo = arrayOf( | |
intArrayOf(0, 1, 2), intArrayOf(3, 4, 5), intArrayOf(6, 7, 8), // horizontal bingo | |
intArrayOf(0, 3, 6), intArrayOf(1, 4, 7), intArrayOf(2, 5, 8), // vertical bingo | |
intArrayOf(0, 4, 8), intArrayOf(2, 4, 6) // diagonal bingo | |
) | |
// Check bingo cases | |
for (it in bingo) { | |
if (board[it[0]] in arrayOf("O", "X") && board[it[0]] === board[it[1]] && board[it[1]] === board[it[2]]) { | |
println( | |
when (turn) { | |
0 -> "You won! Congratulation!" | |
else -> "You lose.. Try again!" | |
} | |
) | |
break@game | |
} | |
} | |
if (board.count { it == " " } == 0) { | |
println("Draw!") | |
break@game | |
} | |
/* Check game is over End*/ | |
turn = turn xor 1 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment