初级三子棋: 首先定义一个3*3棋盘,然后玩家先下,电脑利用时间作为随机种子生成随机数,然后确定棋子位置.可以判断其谁赢及和棋 其逻辑流程图如下: 主函数流程图 游戏流程图
主函数代码:主函数用while(1)循环可以实现连续一局又一局的玩,直到想退出
int main() { int a = 0; while (1) //游戏循环 { printf(" 三子棋 \n"); printf("******************************\n"); printf(" 1.开始游戏 \n"); printf(" 0.退出 \n"); printf("******************************\n"); printf("请输入选择:"); scanf("%d", &a); if (a == 1) SanZiQi(); if (a == 0) break; if (a != 1 && a != 0) continue; } system("pause"); return 0; }初始化模块及显示模块:
#include<stdio.h> #include<windows.h> #include<stdlib.h> #include<time.h> #define MAXTHREE 3 char three[MAXTHREE][MAXTHREE]; //三子棋数组 void InitThree() //初始化三子棋盘 { for (int i = 0; i < MAXTHREE; i++) { for (int j = 0; j < MAXTHREE; j++) { three[i][j] = ' '; } } } void Display() //显示三子棋盘 { for (int i = 0; i < MAXTHREE; i++) { printf(" ___ ___ ___ \n\n"); for (int j = 0; j < MAXTHREE; j++) { printf("| %c ", three[i][j]); } printf("|\n"); } printf(" ___ ___ ___ \n\n"); }游戏模块逻辑控制:
void SanZiQi() { system("cls"); InitThree(); //显示棋盘 Display(); while (1) { //玩家下子; PlayerInput(); system("cls"); printf("玩家落子:\n"); Display(); Sleep(1000); //判断输赢 if (IsWin() == 1) { break; } system("cls"); //电脑下子 ComputerInput(); printf("电脑落子:\n"); Display(); //判断输赢 if (IsWin() == 1) { break; } Sleep(1000); } Sleep(1000); }玩家下棋模块:检测玩家输入,并判断其是否在合理范围即是否在棋盘中,及该位置是否是空的
void PlayerInput() //玩家输入 { while (1) { int row = 0; int col = 0; printf("请输入坐标:"); scanf("%d %d", &row, &col); if (row < 0 || row >= MAXTHREE) continue; if (col < 0 || col >= MAXTHREE) continue; if (three[row][col] != ' ') continue; else { three[row][col] = '*'; break; } } }电脑下棋模块:通过随机数,生成棋子位置,并判断该位置是否为空,不为空,重新生成
void ComputerInput() { srand((int)time(0)); while (1) { int col = rand() % 3; int row = rand() % 3; if (three[row][col] != ' ') continue; else { three[row][col] = 'o'; break; } } }判断输赢模块:通过行列检测是否为同一字符,注意空字符除外,并且检测两条对角线
int IsWin() { for (int i = 0; i < MAXTHREE; i++) { if (three[i][0] == three[i][1] && three[i][2] == three[i][1]&&three[i][0]!=' ') { if (three[i][0] == '*') { printf("玩家赢!\n"); return 1; } if (three[i][0] == 'o') { printf("电脑赢!\n"); return 1; } } } for (int i = 0; i < MAXTHREE; i++) { if (three[0][i] == three[1][i] && three[1][i] == three[2][i] && three[0][i] != ' ') { if (three[0][i] == '*') { printf("玩家赢!\n"); return 1; } if (three[0][i] == 'o') { printf("电脑赢!\n"); return 1; } } } if (three[0][0] == three[1][1] && three[1][1] == three[2][2] && three[0][0] != ' ') { if (three[0][0] == '*') { printf("玩家赢!\n"); return 1; } if (three[0][0] == 'o') { printf("电脑赢!\n"); return 1; } } if (three[0][2] == three[1][1] && three[1][1] == three[2][0] && three[2][0] != ' ') { if (three[2][0] == '*') { printf("玩家赢!\n"); return 1; } if (three[2][0] == 'o') { printf("电脑赢!\n"); return 1; } } int num=0; for (int i = 0; i < MAXTHREE; i++) //和棋 { for (int j = 0; j < MAXTHREE; j++) { if (three[i][j] != ' ') num++; } } if (num == 9) { printf("和棋\n"); return 1; } return 0; }