對於tic tac toe遊戲,我有一個Board
類,它將遊戲板存儲在二維數組中。現在我正在處理項目的AI部分,我想我需要保留Board
類中的未佔用單元列表或在AIPlayer
類中生成列表。但是,由於我使用的是二維數組,我不確定如何去做這件事。如何存儲或生成2d索引列表
這樣做的最好方法是什麼?
這裏是我的主板類: 頭文件:
#pragma once // include guard
#include <iostream>
class Board
{
public:
Board();
void displayBoard() const;
char getCell(int row, int column) const;
void setCell(int row, int column, char player);
bool isWon(char token) const;
bool isDraw()const;
private:
char board[3][3];
int occupiedCells;
};
實現文件:
#include "Board.h"
#include <iostream>
Board::Board()
{
occupiedCells = 0;
for (int row = 0; row < 3; row++)
{
for (int column = 0; column < 3; column++)
board[row][column] = ' ';
}
}
void Board::displayBoard() const
{
std::cout << "\n-------------" << std::endl;
for (int row = 0; row < 3; row++)
{
std::cout << "| " ;
for (int column = 0; column < 3; column++)
std::cout << board[row][column] << " | ";
std::cout << "\n-------------" << std::endl;
}
}
char Board::getCell(int row, int column) const
{
return board[row][column];
}
void Board::setCell(int row, int column, char player)
{
board[row][column] = player;
occupiedCells ++;
}
bool Board::isWon(char token) const
{
// Check rows
for (int i = 0; i < 3; i++)
if (token == board[i] [0] && token == board[i] [1] && token == board[i] [2]) return true;
// Check columns
for (int j = 0; j < 3; j++)
if (token == board[0] [j] && token == board[1] [j] && token == board[2] [j]) return true;
// Check diagonals
if (token == board[0] [0] && token == board[1] [1] && token == board[2] [2]) return true;
if (token == board[0] [2] && token == board[1] [1] && token == board[2] [0]) return true;
return false;
}
bool Board::isDraw() const
{
if (occupiedCells == 9)
{
return true;
}
return false;
}
這裏是我的AIPlayer類: 頭文件:
#pragma once // include guard
#include "Player.h"
class AIPlayer: public Player
{
public:
AIPlayer(char token);
virtual void makeAMove(Board &myBoard);
};
實施文件:
#include <stdlib.h> // rand, srand
#include <time.h> // time
#include "AIPlayer.h"
AIPlayer::AIPlayer(char token) : Player(token)
{
}
void AIPlayer::makeAMove(Board &myBoard)
{
int row;
int column;
srand (time(0));
bool done = false;
do
{
row = rand() % 3;
column = rand() % 3;
if (myBoard.getCell(row, column) == ' ')
{
myBoard.setCell(row, column, getToken());
done = true;
}
}
while (!done);
std::cout << "\nComputer move (" << getToken() << ")\n"
"row " << row << ", column " << column;
}
我只想與指數一個數字爲0到8,並用'x = n%3'和'y = n/3'轉換爲xy。然後相反,'n =(y * 3)+ x'。 –