标签:棋盘游戏、二维数组
#define _CRT_SECURE_NO_WARNINGS 1 #include <stdio.h> #include <stdlib.h> char matrix[3][3]; //宏定义一个二维数组,表示棋盘 void init_matrix(void ) //初始化数组 { int i, j; for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { matrix[i][j] = ‘ ‘; } } } void dis_matrix( ) //打印棋盘的格式 { int t; for (t = 0; t < 3; t++) { printf( " %c | %c | %c ", matrix[t][0], matrix[t][1], matrix[t][2]); if (t != 2) printf( "\n---|---|---\n"); } printf( "\n"); } void get_player_move(void ) //玩家下棋 { int x, y; printf( "请输入你要下棋的位置x和y: " ); scanf( "%d %d", &x, &y); x--; y--; if (matrix[x][y] != ‘ ‘ ) { printf( "请再一次输入:\n" ); get_player_move(); } else matrix[x][y] = ‘X‘; } void get_computer_move() //电脑下棋 { int i, j; for (i = 0; i < 3; i++) /*从(,)一直遍历到(,3), 有空格时电脑下棋*/ { for (j = 0; j < 3; j++) { if (matrix[i][j] == ‘ ‘ ) break; } if (matrix[i][j] == ‘ ‘ ) break; } if (i*j == 9) //判断棋盘是否下满 { printf( "draw\n"); exit(0); } else matrix[i][j] = ‘0‘; } char check( ) //判断下棋输赢 { int i; for (i = 0; i < 3; i++) { if (matrix[i][0] == matrix[i][1] && matrix[i][1] == matrix[i][2]) return matrix[i][0]; } for (i = 0; i < 3; i++) { if (matrix[0][i] == matrix[1][i] && matrix[1][i] == matrix[2][i]) return matrix[0][i]; } if (matrix[0][0] == matrix[1][1] && matrix[1][1] == matrix[2][2]) return matrix[0][0]; if (matrix[0][2] == matrix[1][1] && matrix[1][1] == matrix[2][0]) return matrix[0][2]; return ‘ ‘ ; } int main() { char done=‘ ‘; printf( "请进入下棋游戏.\n" ); init_matrix(); do { dis_matrix(); get_player_move(); done = check(); if (done != ‘ ‘ ) break; get_computer_move(); done = check(); } while (done == ‘ ‘ ); if (done == ‘X‘ ) printf( "player won !!!!\n"); else printf( "computer won!!!!\n"); dis_matrix(); system("pause"); return 0; }
本文出自 “无心的执着” 博客,请务必保留此出处http://10740590.blog.51cto.com/10730590/1706022
标签:棋盘游戏、二维数组
原文地址:http://10740590.blog.51cto.com/10730590/1706022