使用rand()函数在Tic-Tac-Toe中创建计算机侧移动时遇到困难



我一直在尝试制作井字游戏。我首先编码了一个双人游戏,它可以工作,但后来试图通过在随机插槽上放置一个标记来使一侧计算机化,但找不到它为什么不能正常工作的问题。我们获得了第一次机会并选择了标记,但在那之后,comp应该打一个空位,但它再次要求我们打第二步。大多数情况下,函数的编写和调用顺序都变得混乱,任何帮助都将不胜感激!

#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
char board[3][3] = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};
char current_marker;
int current_player;
int comp_slot;

void drawBoard(){
cout<< "     |       |    "<<endl;
cout<<"  "<<board[0][0]<<"  |   "<<board[0][1]<<"   |   "<<board[0][2]<<endl;
cout<< "_____|_______|_____"<<endl;
cout<< "     |       |    "<<endl;
cout<<"  "<<board[1][0]<<"  |   "<<board[1][1]<<"   |   "<<board[1][2]<<endl;
cout<< "_____|_______|_____"<<endl;
cout<< "     |       |    "<<endl;
cout<<"  "<<board[2][0]<<"  |   "<<board[2][1]<<"   |   "<<board[2][2]<<endl;
cout<< "     |       |     "<<endl;
}

bool placeMarker(int slot){
int row = slot/3;
int col;
if(slot % 3 == 0){
row = row - 1;
col = 2;
}
else{
col = (slot % 3) - 1;
}

if(board[row][col] != 'X' && board[row][col] != 'O'){
board[row][col] = current_marker;
return true;
}
else return false;
}

int winner(){
for(int i=0; i<9; i++){
//row
if(board[i][0] == board[i][1] && board[i][1] && board[i][2]){
return current_player;
}
if(board[0][i] == board[1][i] && board[1][i] == board[2][i]){
return current_player;
}
}
//for diagonals
if(board[0][0] == board[1][1] && board[1][1] == board[2][2]){
return current_player;
}
if(board[0][2] == board[1][1] && board[1][1] == board[2][0]){
return current_player;
}
return 0;
}

void swap_player_marker(){
if(current_marker == 'X') current_marker = 'O';
else current_marker = 'X';
if(current_player == 1) current_player = 2;
else current_player = 1;
}

void game(){
//players
string name1, name2;
cout<<"Enter your name: ";
cin>>name1;

cout<<name1<<" choose your marker: "; 
char h_marker; //X
cin>>h_marker; 
current_player = 1;
current_marker = h_marker; //X

drawBoard();
int player_won;
for(int i=0; i<4; i++){
cout<<"It's your turn. Enter slot: ";
int slot;
cin>> slot;
if(slot < 1 || slot > 9){
cout<<"Slot invalid! Try another slot!"<<endl;
i--;
continue;
}

if(!placeMarker(slot)){
cout<<"Slot occupied! Try another slot!"<<endl;
i--;
continue;
}

drawBoard();
player_won = winner();
if(player_won == 1){
cout<<"You won! Congratulations!";
break;
}
if(player_won == 2){
cout<<"Comp won! Congratulations!";
break;
}
int comp_slot = (rand() % (10 - 1 + 1)) + 1;

if(!placeMarker(comp_slot)){
cout<<"Slot occupied! Try another slot!"<<endl;
i--;
continue;
}
swap_player_marker();
}
if(player_won == 0){
cout<<"This game is a TIE";
}
}

int main(){
game();
}

在使用rand之前添加srand((undesigned)time(0)),否则每次数字都会重复。

相关内容

最新更新