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

코틀린 프로그래밍 기본 1

임시 이미지 황영덕
http://www.boostcourse.org/mo132/forum/40961
좋아요 647 수강생 4341
var x: Int = 0
var y: Int = 0

fun main(){
var board = Array<CharArray>(3) { CharArray(3) }
initBoard(board)

val names = arrayOf("Player 1", "Player 2")
val marks = arrayOf('O', 'X')

play(board, names, marks)
}

fun initBoard(board: Array<CharArray>){
for(i in 0..2){
for(j in 0..2)
board[i][j] = ' '
}
}

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

for(y in 0..2){
print("$y ")
for(x in 0..2){
print("${board[y][x]}")
if(x!=2) print("|")
}
println()
if(y!=2){
print(" ")
for(x in 0..2){
print("-")
if(x!=2) print("+")
}
println()
}
}
}

val isInRange = {x: Int, y: Int -> x in 0..2 && y in 0..2 }

fun isValid(board: Array<CharArray>, x: Int, y: Int): Boolean{
return isInRange(x, y) && board[y][x] == ' '
}

fun playerInput(name: String, board: Array<CharArray>): Boolean{
print("$name 입(줄,칸): ")
val input: String? = readLine()
val arr = input!!.split(",")
y = arr[0].toInt()
x = arr[1].toInt()
if(!isValid(board, x, y)) return false
return true
}

fun play(board: Array<CharArray>, names: Array<String>, marks: Array<Char>){
var round = 0
var turn = 0

while(true){
println("\n ${turn+1}번째 턴")
printBoard(board)
if(!playerInput(names[turn], board))
continue
board[y][x] = marks[turn]
round++
if(isWin(board, x, y)){
printBoard(board)
println("${names[turn]} 승리!")
break
}else{
if(round == 9){
printBoard(board)
println("무승부 입니다.")
break
}
}
turn = if(turn==1) 0 else 1
}
}

fun isWin(board: Array<CharArray>, x: Int, y: Int): Boolean{
val dx = arrayOf(-1, 1, 0, 0, -1, 1, 1, -1)
val dy = arrayOf(0, 0, -1, 1, -1, 1, -1, 1)

for(i in 0..3){
var count = 1;
for(j in 0..1){
val index = 2*i+j
var cx = x + dx[index]
var cy = y + dy[index]
while(isInRange(cx, cy)){
if(board[y][x]==board[cy][cx]) count++
cx += dx[index]
cy += dy[index]
}
}
if(count == 3) return true
}
return false
}