使用 Groovy 的简单井字游戏(switch 语句中的索引不更改双数组中的元素)
Simple Tic Tac Toe using Groovy (Index in switch statement not changing element in double array)
我是 Groovy 的新手,我一直在尝试制作一个简单的井字游戏。由于那里没有与 groovy 相关的资源,我一直在关注一个 Java 项目并试图将其转换为 groovy。到目前为止一切正常,但我的 switch 语句中的数据没有用 X 替换双数组中的 space。我尝试调试它但找不到问题所在。
下面是代码:
`def gameBoard = [[' ','|',' ','|',' '],
['-','+','-','+','-'],
[' ','|',' ','|',' '],
['-','+','-','+','-'],
[' ','|',' ','|',' ']] as char[][]
//user needs to put a piece in one of the spaces, can do this my doing indexes but easier to number boxes 1-9
println "Enter your placement 1-9"
def input = System.in.newReader().readLine()
println input
//changing a symbol (changing the space characters with our own symbol)
switch(input){
//first row, first char
case 1:
gameBoard[0][0] = 'X'
break
case 2:
gameBoard[0][2] = 'X'
break
case 3:
gameBoard[0][4] = 'X'
break
case 4:
gameBoard[2][0] = 'X'
break
case 5:
gameBoard[2][2] = 'X'
break
case 6:
gameBoard[2][4] = 'X'
break
case 7:
gameBoard[4][0] = 'X'
break
case 8:
gameBoard[4][2] = 'X'
break
case 9:
gameBoard[4][4] = 'X'
break
}
printGameBoard(gameBoard)
//print gameBoard[0][1]
static def printGameBoard( gameBoard){
//print out the game board using 2 for loops
//for each array(row) inside of the game board, for each char (c) inside of the row, we are going to print out the symbol
for(char[] row : gameBoard){
for(char c : row){
print c
}
println()
}
}
`
System.in.newReader().readLine() returns 字符串,在 switch/case 中你尝试将它与 int.
进行比较
简单添加 as int
应该可以解决您的问题
def input = System.in.newReader().readLine() as int
我是 Groovy 的新手,我一直在尝试制作一个简单的井字游戏。由于那里没有与 groovy 相关的资源,我一直在关注一个 Java 项目并试图将其转换为 groovy。到目前为止一切正常,但我的 switch 语句中的数据没有用 X 替换双数组中的 space。我尝试调试它但找不到问题所在。 下面是代码:
`def gameBoard = [[' ','|',' ','|',' '],
['-','+','-','+','-'],
[' ','|',' ','|',' '],
['-','+','-','+','-'],
[' ','|',' ','|',' ']] as char[][]
//user needs to put a piece in one of the spaces, can do this my doing indexes but easier to number boxes 1-9
println "Enter your placement 1-9"
def input = System.in.newReader().readLine()
println input
//changing a symbol (changing the space characters with our own symbol)
switch(input){
//first row, first char
case 1:
gameBoard[0][0] = 'X'
break
case 2:
gameBoard[0][2] = 'X'
break
case 3:
gameBoard[0][4] = 'X'
break
case 4:
gameBoard[2][0] = 'X'
break
case 5:
gameBoard[2][2] = 'X'
break
case 6:
gameBoard[2][4] = 'X'
break
case 7:
gameBoard[4][0] = 'X'
break
case 8:
gameBoard[4][2] = 'X'
break
case 9:
gameBoard[4][4] = 'X'
break
}
printGameBoard(gameBoard)
//print gameBoard[0][1]
static def printGameBoard( gameBoard){
//print out the game board using 2 for loops
//for each array(row) inside of the game board, for each char (c) inside of the row, we are going to print out the symbol
for(char[] row : gameBoard){
for(char c : row){
print c
}
println()
}
}
`
System.in.newReader().readLine() returns 字符串,在 switch/case 中你尝试将它与 int.
进行比较简单添加 as int
应该可以解决您的问题
def input = System.in.newReader().readLine() as int