本文主要是介绍三子棋小游戏c语言实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
# define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include<stdlib.h>
#include<time.h>
#define max_row 3
#define max_col 3
//初始化
void init(char board[max_row][max_col]) {
for (int row = 0; row < max_row; row++) {
for (int col = 0; col < max_col; col++) {
board[row][col] = ' ';
}
}
//设置随机种子
srand((unsigned int)time(0));
}
//打印棋盘
void printBoard(char board[max_row][max_col]) {
system("cls");
for (int row = 0; row < max_row; row++) {
printf("+---+---+---+\n");
for (int col = 0; col < max_col; col++) {
printf("| %c ", board[row][col]);
}
printf("|");
printf("\n");
}
printf("+---+---+---+\n");
}
//玩家移动
void playerMove(char board[max_row][max_col]) {
printf("请玩家落子\n");
while (1) {
printf("请输入落子的位置(row,col)");
int row = 0, col = 0;
scanf("%d %d", &row, &col);
if (row < 0 || row >= max_row || col < 0 || col >= max_col) {
printf("输入有误,请重新输入\n");
continue;
}
if (board[row][col] != ' ') {
printf("当前位置已经有子了,无法落子\n");
continue;
}
board[row][col] = 'x';
break;
}
}
void computerMove(char board[max_row][max_col]) {
//轮到电脑落子
while (1) {
if (isFull(board)) {
break;
}
int row = rand() % max_row;
int col = rand() % max_col;
if (board[row][col] != ' ') {
//说明位置已经有子了
continue;
}
board[row][col] = 'o';
printBoard(board);
break;
}
}
int isFull(char board[max_row][max_col]) {
//棋盘里面有空格就是没满,没空格就是满了
for (int row = 0; row < max_row; row++) {
for (int col = 0; col < max_col; col++) {
if (board[row][col] == ' ') {
return 0;
}
}
}
return 1;
}
char checkWinner(char board[max_row][max_col]) {
//1.检测所有行
for (int row = 0; row < max_row; row++) {
if (board[row][0] != ' ' && board[row][0] == board[row][1] && board[row][1] == board[row][2]) {
return board[row][0];
}
}
//2.检查所有列
for (int col = 0; col < max_col; col++) {
if (board[0][col] != ' ' && board[0][col] == board[1][col] && board[1][col] == board[2][col]) {
return board[0][col];
}
}
//3.检查所有对角线
if (board[0][0] != ' ' && board[0][0] == board[1][1]
&& board[0][0] == board[2][2]
) {
return board[0][0];
}
if (board[2][0] != ' ' && board[2][0] == board[1][1]
&& board[2][0] == board[0][2]
) {
return board[2][0];
}
//4.检查是否和棋
if (isFull(board)) {
return 'q';
}
return ' ';
}
int main() {
//1.初始化棋盘
char board[max_row][max_col] = { 0 };
init(board);
char winner = ' ';
// 2.打印棋盘
printBoard(board);
while (1) {
//玩家落子
playerMove(board);
//电脑落子
computerMove(board);
//判定胜负 玩家胜返回x,电脑胜返回'o',和棋返回'q',胜负未分返回' '
winner = checkWinner(board);
if (winner == 'x') {
printf("玩家获胜");
}
if (winner == 'o') {
printf("电脑获胜");
}
if (winner == 'q') {
printf("和棋");
}
if (winner != ' ') {
//胜负已分 结束游戏
break;
}
}
return 0;
}
基本的功能是ok的,但是还有一些地方有些小问题,就是判断结束的时候
这篇关于三子棋小游戏c语言实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!