我希望有人可以帮助我,我真的很挣扎着我的代码。我正在构建一个简单的Java游戏,你可以使用坐标将X移动到棋盘上的另一个空间,我只是想知道如何在(1,1)处移动它并将其移动到另一个地方。感谢。
package ai;
/**
*
* @author x12388761
*/
import java.util.Scanner;
public class AI {
public static String[][] board = new String[10][10];
public static void addPiece(int x, int y, String r){
board[x][y] = r;//no need for new String(), board is already made of Strings.
}
public static void showBoard(){
//it's generally better practice to initialize loop counters in the loop themselves
for (int row = 0; row < 9; row++)
{
System.out.println(" ");
System.out.println("-------------------");
for(int col = 0; col < board[row].length; col++)
{
System.out.print("|"); //you're only printing spaces in the spots
if(board[col][row] == null){
System.out.print(" ");
}else{
System.out.print(board[col][row]);
}
}
}
System.out.println(" ");
System.out.println("-------------------");
}
public static void main(String[] args) {
addPiece(0,0," ");
addPiece(0,1,"1");
addPiece(0,2,"2");
addPiece(0,3,"3");
addPiece(0,4,"4");
addPiece(0,5,"5");
addPiece(0,6,"6");
addPiece(0,7,"7");
addPiece(0,8,"8");
addPiece(1,0,"1");
addPiece(2,0,"2");
addPiece(3,0,"3");
addPiece(4,0,"4");
addPiece(5,0,"5");
addPiece(6,0,"6");
addPiece(7,0,"7");
addPiece(8,0,"8");
addPiece(1,1,"X");
addPiece(8,8,"O");
showBoard();
Scanner myScan = new Scanner(System.in);
System.out.println("Would you like to go first? Yes or No");
String goFirst = myScan.nextLine();
if(goFirst.equals("yes") || goFirst.equals("Yes") || goFirst.equals("YES")) {
System.out.println("You are X! Please enter the coordinates of your first move");
String coordinate = myScan.nextLine();
String[] parts = coordinate.split(",");
String x = parts[0];
String y = parts[1];
System.out.println("Moving to (" + x +","+ y +")");
}
if(goFirst.equals("no") || goFirst.equals("No") || goFirst.equals("NO")) {
System.out.println("You are O! The computer will make the first move.");
}
}
}
答案 0 :(得分:1)
/** Move 1 to 2, 1 is empty after move */
public static void move(int x1, int y1, int x2, int y2) {
board[x2][y2] = board[x1][y1];
board[x1][y1] = " ";
}
这是有效的,因为2
设置为1
,然后1
设置为空。这没有检查以确保2
为空或1
有一块。如果你想检查一下,你需要使用它:
/** Move 1 to 2, 1 is empty after move */
public static void move(int x1, int y1, int x2, int y2) {
if (!board[x1][y1].equals(" ") && board[x2][y2].equals(" ")) {// if 1 is not empty
// and 2 is empty
board[x2][y2] = board[x1][y1];
board[x1][y1] = " ";
}
}
加分:改进代码的方法
当您询问用户他是否想先行时,您使用String.equals
检查输入,这是一个艰难的方法。在这种情况下,您应该使用String.equalsIgnoreCase
,即goFirst.equalsIgnoreCase("yes")
。
在show board方法中,您可以使用:
System.out.println(" ");
System.out.println("-------------------");
可以使用特殊换行符println
加入两个\n
,如下所示:
System.out.println("\n-------------------");
答案 1 :(得分:0)
判断用户输入是或否,您可以使用equalsIgnoreCase方法。此方法忽略大写或小写。如下所示:
String upper = "YES";
String lower = "yes";
upper.equalsIgnoreCase(lower);// true
如果String lower =&#34; YeS&#34 ;;结果也一样。