로그인 바로가기 하위 메뉴 바로가기 본문 바로가기
난이도
입문

코틀린 프로그래밍 기본 1

임시 이미지 황영덕
http://www.boostcourse.org/mo132/forum/32121
좋아요 647 수강생 4341

코틀린으로 작성한 첫 프로젝트입니다!

코틀린 스러운 느낌은 부족하지만 완성에 의미를 두고 제출합니다 ^^


+ 문자를 입력받고 처리할 때 더 쉽고 간단한 방법이 없을까 궁금하네요


package FinalProjects

data class Players(val name: String = "", val mark: Char = ' ')

fun initBoard(): Array<CharArray> {
val board: Array<CharArray> = Array<CharArray>(3) { CharArray(3) }

for (i in 0..2)
for (j in 0..2)
board[i][j] = ' '

return board
}

fun printBoard(board: Array<CharArray>) {
print(" ")
for (i in 0..board.lastIndex) print(" $i")
println()

for (i in 0..board.lastIndex) {
print("$i ")
for (j in 0..board.lastIndex) {
print(board[i][j])
if (j == board.lastIndex) println() else print('|')
}

if (i == board.lastIndex) println() else print(" -+-+-")
}
}

fun isInRange(x: Int, y: Int) = x in 0..2 && y in 0..2

fun isValid(board: Array<CharArray>, x: Int, y: Int) = board[x][y] == ' '

fun playerInput(board: Array<CharArray>, player: Players): Boolean {
val x: Int
val y: Int

try {
print("${player.name} 입력(줄,칸): ")
val coordinates = readLine()!!.split(',').map { it.toInt() }

x = coordinates[0]
y = coordinates[1]
} catch (e: Exception) {
println(e.message)
return false
}

return if (isInRange(x, y) && isValid(board, x, y)) {
board[x][y] = player.mark
true
} else
false
}

fun isWin(board: Array<CharArray>, player1: Players, player2: Players): Boolean {
fun isWinner(player: Players): Boolean {
val mark = player.mark

for (i in 0..2) {
if (board[i][0] == mark && board[i][1] == mark && board[i][2] == mark) return true
if (board[0][i] == mark && board[1][i] == mark && board[2][i] == mark) return true
}
if (board[0][0] == mark && board[1][1] == mark && board[2][2] == mark) return true
if (board[0][2] == mark && board[1][1] == mark && board[2][0] == mark) return true

return false
}

return when {
isWinner(player1) -> {
printBoard(board)
println("${player1.name} 승리!")
true
}
isWinner(player2) -> {
printBoard(board)
println("${player2.name} 승리!")
true
}
else -> {
false
}
}
}

fun play(board: Array<CharArray>, player1: Players, player2: Players) {
var turn = 1

while (turn < 10 && !isWin(board, player1, player2)) {
println("${turn}번째 턴")
printBoard(board)

val result = if (turn % 2 == 1) playerInput(board, player1) else playerInput(board, player2)
if (result)
turn++
}
if (turn == 10) printBoard(board)
}

fun main() {
val board = initBoard()
val player1 = Players("Player1", 'O')
val player2 = Players("Player2", 'X')

play(board, player1, player2)
}