我正在创建一个名为 SOS 的游戏。这是一款 3x3 棋盘游戏,与井字游戏具有相同的概念,但在此游戏中,玩家无法选择玩 X 或 O,游戏中唯一的规则是形成“SOS”。
我们的程序应该在所有位置都填满后终止,每个形成的“SOS”都会添加到形成“SOS”的玩家身上。
我的问题是关于得分。在第一行输入 SOS 后(- - -)
,我尝试在第二行第一列输入“O”,播放器 2 将递增。它不应该增加,因为它不满足第二个 else if 在我的程序中。为什么会这样?
这是我的代码:
import java.util.Scanner;
public class SOS
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String ar[] = {"-","-","-","-","-","-","-","-","-"};
int player1 = 0;
int player2 = 0;
int index = 0;
for(int l = 0; l<3; l++)
{
for(int j = 0; j<3; j++)
{
System.out.print(ar[j]);
}
System.out.print("\n");
}
for(int j = 0;j < 9;j++)
{
//Input position and letter
System.out.println("Enter the position number: ");
index = input.nextInt();
input.nextLine();
System.out.println("Enter (S or O): ");
ar[index - 1] = input.nextLine();
//Output for the game
for(int l = 0; l<9; l++)
{
System.out.print(ar[l]);
if(l == 2)
{
System.out.println();
}
else if(l == 5)
{
System.out.println();
}
else if(l == 8)
{
System.out.println();
}
}
//condition
if((ar[0]+ar[1]+ar[2]).equals("SOS"))
{
if(j%2 == 0)
{
player1++;
System.out.println("Player 1: "+player1+" Player 2: "+player2);
}
else if( j % 2 != 0)
{
player2++;
System.out.println("Player 1: "+player1+" Player 2: "+player2);
}
}
else if((ar[3]+ar[4]+ar[5]).equals("SOS"))
{
if(j%2 == 0)
{
player1++;
System.out.println("Player 1: "+player1+" Player 2: "+player2);
}
else if( j % 2 != 0)
{
player2++;
System.out.println("Player 1: "+player1+" Player 2: "+player2);
}
}
else
{
System.out.println("Player 1: "+player1+" Player 2: "+player2);
}
//end of condition
}
}
}