이 포럼에서 질문을하는 것은 이번이 처음입니다. 연습을 위해 tic-tac-toe 게임을 만들었고 열거자를 사용하지 않았고 재귀를 사용하고 있습니다. 열거를 한 번도 해본 적이 없기 때문에 항상 재귀 연습을 할 수 있기 때문입니다. 어쨌든 난 그냥 플레이어 2가 무작위로 이동하도록 코딩을 마쳤습니다. 약 3 번 켜면 세분화 오류가 발생하고 이유를 파악할 수 없습니다 ... 여러분이 알아서 감사드립니다. 당신이 때마다 srand(time(NULL))
를 호출하기 때문에세그먼트 오류 : 11 C++ 오류
#include <iostream>
#include <string>
#include <cstdlib>
const int size = 3;
enum play {none,X,O};
void NPC(play (&board)[size][size],play player2) {
srand(time(NULL));
int tempx = rand() % 3;
int tempy = rand() % 3;
if(board[tempx][tempy] == none)
board[tempx][tempy] = player2;
else
NPC(board,player2);
}
void getBoardState(play (&board)[size][size],int y,int x) {
if(board[x][y] == none) std::cout << " ";
else if(board[x][y] == X) std::cout << "X";
else std::cout << "O";
}
void printboard(play (&board)[size][size]){
int length = 4 * size - 1;
for(int i = 1; i <= length; i++) {
for(int j = 1; j <= length; j++) {
if(i % 4 == 0 && j % 4 == 0) std::cout << "+";
else if(i % 4 == 0) std::cout << "-";
else if(j % 4 == 0) std::cout << "|";
else if(i % 2 == 0 && j % 2 == 0) getBoardState(board,(i - 2)/4,(j - 2)/4);
else std::cout << " ";
}
std::cout << std::endl;
}
}
int main() {
play player = O, player2 = X;
bool over = false;
play board[size][size];
for(int i = 0; i < size; i++) {
for(int j = 0; j < size; j++) {
board[i][j] = none;
}
}
std::string player1 = "";
std::cout << "What would You like to be? An X or an O?" << std::endl;
while(((player1 != "X") + (player1 != "O")) == 2) {
std::cin >> player1;
if(((player1 != "X") + (player1 != "O")) == 2)
std::cout << "Invalid entry! Please enter X or an 0!" << std::endl;
}
if(player1 == "X") {
player2 = O;
player = X;}
int tempx,tempy;
while(!over) {
std::cout << "Please enter an x and then a y (1 to " << size << ")" << std::endl;
std::cin >> tempx;
std::cin >> tempy;
while(tempx > size || tempy > size || board[tempx-1][tempy-1] != none) {
std::cout << "Invalid entry! Try again!" << std::endl;
std::cin >> tempx;
std::cin >> tempy;
}
board[tempx-1][tempy-1] = player;
NPC(board,player2);
printboard(board);
}
return 0;
}
보드가 꽉 찼을 때 종료해야합니다. 그렇지 않으면 NPC 기능이 영원히 반복됩니다. –
[rand 함수의 가능한 복제본은 단일 함수 내에서 호출 될 때 같은 값을 반환합니다. C++] (http://stackoverflow.com/questions/6729214/rand-function-returns-same-values-when-called-within-a-single -function-c) –