/*
============================================================================
Name : jingziyouxi.c
Author : zhangcheng
Version :
Copyright : Your copyright notice
Description : 类似5指棋。当你的指先占满行列或对角线,你就赢了。两个玩家用1和2表示。
玩家1的指用'x'表示,玩家二的指用'o'表示。玩家1先开始。初始化给子里面
放123456789.玩家通过输入对应的数字,把指放在相应的格子里。
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int player = 0;
int winner = 0;
int choice = 0;
unsigned int row = 0;
unsigned int column = 0;
char board[3][3] = {
{'1', '2', '3'},
{'4', '5', '6'},
{'7', '8', '9'}
};
//the mian game loop. The game continues for up to 9 turns as long as there is no winner
for(unsigned int i = 0; i < 9 && winner == 0; ++i){
printf("\n");
printf("%c | %c | %c\n", board[0][0], board[0][1], board[0][2]);
printf("--+---+--\n");
printf("%c | %c | %c\n", board[1][0], board[1][1], board[1][2]);
printf("--+---+--\n");
printf("%c | %c | %c\n", board[2][0], board[2][1], board[2][2]);
player = i % 2 + 1; //select player
//进入有效的方格选择
do{
printf("player %d ,please enter a valid square number for "
"where you want to place your %c: ",player, (player == 1) ? 'x' : 'o');
scanf("%d", &choice);
row = --choice / 3; //获得输入数字所在的行号
column = choice % 3; //获得输入数字所在的列号
}while(choice < 0 || choice > 8 || board[row][column] > '9');
//insert player symbol
board[row][column] = (player == 1) ? 'x' : 'o';
//check for a winning line-dialogs first 检查对角线
if( (board[0][0] == board[1][1] && board[0][0] == board[2][2]) ||
(board[0][2] == board[1][1] && board[0][2] == board[2][0]))
winner = player;
else {
//检查非对角线
for(unsigned int line = 0; line <2; ++line){
if((board[line][0] == board[line][1] && board[line][0] == board[line][2]) ||
(board[0][line] == board[1][line] && board[0][line] == board[2][line]) ){
winner = player;
}
}
}
}
//Game is over so display the final board
printf("\n");
printf("%c | %c | %c\n", board[0][0], board[0][1], board[0][2]);
printf("--+---+--\n");
printf("%c | %c | %c\n", board[1][0], board[1][1], board[1][2]);
printf("--+---+--\n");
printf("%c | %c | %c\n", board[2][0], board[2][1], board[2][2]);
//Displsy result message
if(winner){
printf("\ncongratulations, player %d, YOU ARE THE WINNER!\n", winner);
}
else {
printf("\nHow boring, it is a draw\n");
}
return EXIT_SUCCESS;
}
代码来自:《C语言入门经典》
一个C的小游戏
最新推荐文章于 2022-10-27 21:51:35 发布