欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

MODE —— 两个人在计算机上玩圈叉游戏|井字游戏(知识点:二维数组)

发布时间:2025/10/17 54 豆豆
生活随笔 收集整理的这篇文章主要介绍了 MODE —— 两个人在计算机上玩圈叉游戏|井字游戏(知识点:二维数组) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

问题描述:

        让两个人在计算机上玩井字游戏(也称圈叉游戏)。

        井字游戏就是一个3X3的方格,两个人轮流在方格中输入标记X 或者 O 。谁先使自己的3个标记链接成水平,垂直或对角线。谁就是赢家。 

运行结果:



代码部分(代码说明):

#include <stdio.h> int main() { int player = 0; //Current player number -1 or 2?int winner = 0; //The winning player numberunsigned int i = 0;int choice = 0; //Chosen squareunsigned int row = 0; //Row index for a squareunsigned int column = 0; //Column index for a squareunsigned int line = 0;char board[3][3] = { //The board{'1','2','3'}, //Initial values are characters '1' to '9'{'4','5','6'}, //used to select a vacant square{'7','8','9'} //for a player`s turn };//The main game loop, The game continues for up to 9 turns//as loong as there is no winnerfor(i = 0;i < 9 && winner ==0;++i){//Display the boardprintf("\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]);//有一种让两个玩家轮流输入标记的办法,将两个玩家识别为1和2,编号为1的玩家先玩。然后根据轮流的次数决定输入标记的玩家的号码。//轮到奇数号码时候 就由玩家1输入标记。轮到偶数号时,就由玩家2输入标记。player = i%2 + 1; //Select player 1 or 2//Get valid player square selection do{printf("Player %d,please enter a valid square number""for where you want to place your %c: ",player,(player == 1) ? 'X' : 'O'); //轮到一个玩家输入标记时,需要一种方法标记选择出来的方格。可以用1~9的数字标记这9个方格。玩家只需要输入要选择的方格数字。scanf("%d",&choice); row = --choice/3; //Get row index of squarecolumn = choice % 3; //Get column index of square}while(choice < 0 || choice > 8 || board[row][column] > '9'); //有三种可能导致选择无效:*输入的方格数小于0; *输入的方格数大于8; *选择已包含X或者O的方格(因为X O 的字符码都大于9)//Insert player symbloboard[row][column] = (player == 1) ? 'X' : 'O';//Check for a winning line - diagonals 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{//Check row and columns for a winning line for(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;}}/*Code to check for a winner*/}/*Code to output the game*///Game is over so display the final boardprintf("\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]);//Display result message if(winner)printf("\nCongratulation,player %d,YOU ARE THE WONNER!\n",winner);elseprintf("\nHow boring , it is a draw\n");return 0;}

总结

以上是生活随笔为你收集整理的MODE —— 两个人在计算机上玩圈叉游戏|井字游戏(知识点:二维数组)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。