自學C 四月二十日_做了一個三子棋遊戲!!!

Bite_magican發表於2019-04-20

今天週六做了一個三子棋遊戲;除錯還有一點問題;目前看不出來;過兩天再看//TODO;哈哈;溜了

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int Menu(){
printf("\n");
printf(“1.開始遊戲\n”);
printf(“0.結束遊戲\n”);
printf("
\n");
printf(“請輸入您的選擇:”);
int choice = 0;
scanf("%d", &choice);
return choice;
}

#define MAX_ROW 3
#define MAX_COL 3

char chess_board[MAX_ROW][MAX_COL];

void Init(){
for (int row = 0; row < MAX_ROW; ++row){
for (int col = 0; col < MAX_COL; ++col){
chess_board[row][col] = ’ ';
}
}
//設定隨機種子
srand((unsigned int)time(0));
}

void Print(){
for (int row = 0; row < MAX_ROW; ++row){
printf("| %c | %c | %c |\n", chess_board[row][0],
chess_board[row][1], chess_board[row][2]);
if (row != MAX_ROW - 1){
printf("|—|---|—|\n");
}
}
//TODO
//(“pause”);
}

void PlayerMove(){
printf(“玩家落子!\n”);
while (1){
printf(“請輸入落子位置的座標(row col): “);
int row = 0;
int col = 0;
scanf(”%d %d”, &row, &col);
//檢查使用者輸入的座標是否合法
if (row < 0 || row >= MAX_ROW
|| col < 0 || col >= MAX_COL){
printf(“您輸入的座標非法!請重新輸入!\n”);
continue;
}
if (chess_board[row][col] != ’ '){
printf(“您要落子位置已經被佔用了!\n”);
continue;
}
chess_board[row][col] = ‘x’;
break;
}
printf(“玩家落子完畢!\n”);
}

void ComputerMove(){
printf(“電腦落子!\n”);
while (1){
int row = rand() % 3;
int col = rand() % 3;
if (chess_board[row][col] != ’ '){
continue;
}
chess_board[row][col] = ‘o’;
break;
}
printf(“電腦落子完畢!\n”);
}

//如果棋盤滿了, 返回1, 否則返回 0
int IsFull(){
for (int row = 0; row < MAX_ROW; ++row){
for (int col = 0; col < MAX_COL; ++col){
if (chess_board[row][col] == ’ '){
//未滿
return 0;
}
}
}
return 1;
}
//返回值判斷勝負
char CheckWinner(){
//檢查所有行是否連成一條線
for (int row = 0; row < MAX_ROW; ++row){
if (chess_board[row][0] == chess_board[row][1]
&& chess_board[row][0] == chess_board[row][2]){
return chess_board[row][0];

	}
}
//檢查所有列是否連成一條線
for (int col = 0; col < MAX_ROW; ++col){
	if (chess_board[0][col] == chess_board[1][col]
		&& chess_board[0][col] == chess_board[2][col]){
		return chess_board[0][col];
	}
}
//檢查所有對角線是否連成一條線
if (chess_board[0][0] == chess_board[1][1]
	&& chess_board[0][0] == chess_board[2][2]){
	return chess_board[0][0];
}
if (chess_board[0][2] == chess_board[1][1]
	&& chess_board[0][2] == chess_board[2][2]){
	return chess_board[0][2];
}
//棋盤滿並且為分出勝負
if (IsFull()){
	return 'q';
}
return ' ';

}

//自頂向下式的程式開發方法
void Game(){
//1.初始化棋盤
Init();
char winner = ’ ';
while (1){
//2.列印棋盤
Print();
//3.玩家落子
PlayerMove();
//4.檢測勝負
winner = CheckWinner();
if (winner != ’ '){
//勝負已分
break;
}
//5.電腦落子
ComputerMove();
//6.檢測勝負
winner = CheckWinner();
if (winner != ’ '){
break;
}
}
Print ();
if (winner != ‘x’){
printf(“您贏了!\n”);
}else if (winner == ‘o’){
printf(“您真菜,連電腦都下不過!\n”);
}
else if (winner == ‘q’){
printf(“您和電腦五五開!\n”);
}
else{
printf(“程式碼好像bug了!\n”);
}
}

int main(){
while (1){
int choice = Menu();
if (choice == 1){
Game();
}else if (choice == 0){
printf(“goodbye!\n”);
break;
}else{
printf(“您的輸入有誤!\n”);
}
}
system(“pause”);
return 0;
}

相關文章