【发布时间】:2014-01-26 21:00:56
【问题描述】:
我正在创建一个包含 3 x 3 矩形整数数组的井字游戏类,由 2 个人类玩家玩。 “1”用于第一个玩家的移动,“2”用于第二个玩家的移动。目前,我被卡住了,不知道如何确定/检查游戏是否赢了,或者在每一步完成后是否平局。
不幸的是,我一直在检查每个玩家移动后是否赢得或平局,并希望有人能提供帮助。
到目前为止,这是我的代码: 主类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
TicTacToe game = new TicTacToe();
game.PrintBoard();
game.Play();
}
}
}
井字游戏类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class TicTacToe
{
private const int BOARDSIZE = 3; //size of the board
private int[,] board = new int [BOARDSIZE,BOARDSIZE]; // board representation
string player1row, player1column, player2row, player2column;
enum DONE {win1, win2, win3, win4, win5, win6, win7,win8,
win9, win10, win11, win12, win13, win14, win15, win16};
//Default Constructor
public TicTacToe(){
board = new int [3,3] { {0,0,0},{0,0,0},{0,0,0} };
}
int win1 = 1;
public void PrintBoard(){
Console.WriteLine("-----------------------\n"+
"| | | |\n"+
"| {0} | {1} | {2} |\n" +
"|_______|_______|_______|\n"+
"| | | |\n"+
"| {3} | {4} | {5} |\n" +
"|_______|_______|_______|\n"+
"| | | |\n"+
"| {6} | {7} | {8} |\n" +
"|_______|_______|_______|\n",
board[0,0],board[0,1],board[0,2],
board[1,0],board[1,1],board[1,2],
board[2,0],board[2,1],board[2,2]);
}// end PrintBoard method
public void Play(){
while (true)
{
Console.WriteLine("Player 1's turn.");
Console.Write("Player 1: Enter row ( 0 <= row < 3 ): "); //prompt user
player1row = Console.ReadLine(); //get string from user
Console.Write("Player 1: Enter column ( 0 <= row < 3 ): "); //prompt user
player1column = Console.ReadLine(); //get string from user
//Convert string to ints
int p1r = Convert.ToInt32(player1row);
int p1c = Convert.ToInt32(player1column);
// assign marker to desired position
board[p1r, p1c] = 1;
PrintBoard(); // Update board
checkWinner();
Console.WriteLine("\nPlayer 2's turn.");
Console.Write("Player 2: Enter row ( 0 <= row < 3 ): ");
player2row = Console.ReadLine(); //get string from user
Console.Write("Player 2: Enter column ( 0 <= row < 3 ): ");
player2column = Console.ReadLine(); //get string from user
//Convert string to ints
int p2r = Convert.ToInt32(player2row);
int p2c = Convert.ToInt32(player2column);
// assign marker to desired position
board[p2r, p2c] = 2;
PrintBoard(); // Update board
checkWinner();
}
}//end Play method
private bool checkWinner()
{
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
//I WANT TO CHECK FOR A WIN OR DRAW HERE BUT DONT KNOW HOW TO
}}// end class
我想使用 2 个 for 循环检查获胜者,第一个检查行,然后另一个检查列,然后添加 2 个单独的 if 语句来检查对角线,但我真的不知道如何 & 一直暂时卡住了。
【问题讨论】: