C语言入门小项目:三子棋
其中要注意的细节有以下几点:
玩家落子时注意:玩家输入坐标的合法性及坐标是否已经被占用。
电脑落子:我这里以随机落子为例,若落子坐标未被占用则落子成功。
结局:先判断输赢,再判断平局,若没输赢且无平局,则游戏继续。
来简单粗暴地看看代码
#include<stdio.h>
#include"game.h"
void InitBoard(char board[ROW][COL], int row, int col)/初始化棋盘/
{
int i = 0, j = 0;
for (i = 0; i < ROW; i++)
{
for (j = 0; j < COL; j++)
{
board[i][j] = ’ ';
}
}
}
void DisplayBoard(char board[ROW][COL], int row, int col)/打印棋盘/
{
int i = 0;
for (i = 0; i < row; i++)
{
printf(" %c | %c | %c\n", board[i][0], board[i][1], board[i][2]);
if (i != 2)
{
printf("—|---|—\n");
}
}
}
void PlayerMove(char board[ROW][COL], int row, int col)/玩家输入/
{
int i = 0, j = 0, x = 0, y = 0;
while (1)
{
printf(“请输入坐标”);
scanf_s("%d%d", &x, &y);
if (x >= 1 && x <= row&&y >= 1 && y <= col)
{
if (board[x - 1][y - 1] == ' ')
{
board[x - 1][y - 1] = 'X';
break;
}
else
printf("该位置已经被占,请重新输入\n");
}
else
printf("输入错误\n");
}
}
void Computermove(char board[ROW][COL], int row, int col)/电脑输入/
{
printf(“电脑输入\n”);
int i = 0, j = 0;
while (1)
{
i = rand() % row;
j = rand() % col;
if (board[i][j] == ' ')
{
board[i][j] = '0';
break;
}
}
}
char IsWin(char board[ROW][COL], int row, int col)/判断输赢/
{
int i = 0;
if ((board[0][0] == board[1][1]) && board[1][1] == board[2][2]&&board[1][1]!=’ ‘)
{
return board[1][1];
}
if ((board[0][2] == board[1][1]) && board[1][1] ==board[2][0]&&board[0][2]!=’ ')
{
return board[1][1];
}
for (i = 0; i < 3; i++)
{
if ((board[i][1] == board[i][0]) && (board[i][1] == board[i][2])&&board[i][1]!=' ')
{
return board[i][1];
}
}
for (i = 0; i < 3; i++)
{
if ((board[0][i] == board[1][i]) && (board[1][i] == board[2][i]) && board[2][i]!=' ')
{
return board[0][i];
}
}
if (check_full(board, row, col) == 1)
{
return 'Q';
}
return ' ';
}
int check_full(char board[ROW][COL], int row, int col)/判断棋盘是否已满/
{
int i = 0, j = 0;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
if (board[i][j] == ’ ')
return 0;
}
}return 1;
}
void Game()
{
char board[ROW][COL] = { 0 };
InitBoard(board, ROW, COL);
DisplayBoard(board, ROW, COL);
char win = 0;
do{
PlayerMove(board, ROW, COL);
DisplayBoard(board, ROW, COL);
win = IsWin(board, ROW, COL);
if (win != ' ')
break;
Computermove(board, ROW, COL);
DisplayBoard(board, ROW, COL);
win = IsWin(board, ROW, COL);
if (win != ' ')
break;
} while (1);
if (win == 'X')
printf("你赢了\n");
if (win == '0')
printf("你输了\n");
if (win == 'Q')
printf("平局\n");
}
void menu()//开始提示
{
printf("########################\n");
printf("#####1.play 0.exit#####\n");
printf("########################\n");
}
void test()
{
srand((unsigned int)time(NULL));
menu();
int input = 0;
do{
printf(“请选择:->”);
scanf_s("%d", &input);
switch (input)
{
case 1:
Game();
break;
case 0:
printf("退出游戏\n");
break;
default:
printf("输入错误\n");
break;
}
} while (input);
}
这是主体的算法,而一些游戏的开始提示及结束效果小白们则可以根据个人喜好进行编写,虽然是简单的三子棋但本小白也见过某些大神编写的极其炫酷哦!各位也可以自行发挥让普通的三子棋项目与众不同。