使用C语言简单的实现棋盘为5*5的五子棋小游戏,以下为源代码:
#include <stdio.h> #include <stdlib.h> //初始化一个数组 void Init(char arr[5][5]) //arr数组大小可以改变棋盘大小 { int i = 0, j = 0; for (i = 0; i < 5; i++) { for (j = 0; j < 5; j++) { arr[i][j] = ‘ ‘; } } } //打印棋盘 void Print_Cheseboard(char arr[][5]) { int i = 0; for (i = 0; i < 5; i++) { printf("| %c | %c | %c | %c | %c |\n", arr[i][0], arr[i][1], arr[i][2], arr[i][3], arr[i][4]); if (i != 4) { printf("|---|---|---|---|---|\n"); } } } //玩家下棋 void Player_Move(char arr[][5]) { int x = 0; int y = 0; printf("请输入坐标>>> \n"); scanf("%d%d", &x, &y); x -= 1; y -= 1; if (arr[x][y] == ‘ ‘) { arr[x][y] = ‘X‘; } else { printf("输入有误,请重新输入:\n"); Player_Move(arr); } } //电脑下棋 void Computer_Move(char arr[][5]) { int i = 0, j = 0; for (i = 0; i < 5; i++) { for (j = 0; j < 5; j++) { if (arr[i][j] == ‘ ‘) break; } if (arr[i][j] == ‘ ‘) break; } if (i*j == 25) exit(0); else arr[i][j] = ‘0‘; } //战况判断 char Check(char arr[][5]) { int i = 0; for (i = 0; i < 5; i++) { if (arr[i][0] == arr[i][1] && arr[i][1] == arr[i][2] && arr[i][2] == arr[i][3] && arr[i][3] == arr[i][4]) { if (arr[i][0] != ‘ ‘) return arr[i][0]; } } for (i = 0; i < 5; i++) { if (arr[0][i] == arr[1][i] && arr[1][i] == arr[2][i] && arr[2][i] == arr[3][i] && arr[3][i] == arr[4][i]) { if (arr[0][i] != ‘ ‘) return arr[0][i]; } } if (arr[0][0] == arr[1][1] && arr[1][1] == arr[2][2] && arr[2][2] == arr[3][3] && arr[3][3] == arr[4][4]) { if (arr[0][0] != ‘ ‘) return arr[0][0]; } if (arr[0][4] == arr[1][3] && arr[1][3] == arr[2][2] && arr[2][2] == arr[3][1] && arr[3][1] == arr[4][0]) { if (arr[0][4] != ‘ ‘) return arr[0][4]; } return ‘ ‘; } //主函数 int main() { char done=‘ ‘; char arr[5][5]; Init(arr); do { Print_Cheseboard(arr); Player_Move(arr); done = Check(arr); if (done != ‘ ‘) { break; } Computer_Move(arr); done = Check(arr); } while (done == ‘ ‘); if (done == ‘X‘) { printf("玩家胜!!!\n"); } else { printf("电脑胜!!!\n"); } Print_Cheseboard(arr); system("pause"); return 0; }
本文出自 “木木侠” 博客,谢绝转载!
原文地址:http://10324228.blog.51cto.com/10314228/1716892