C# · 12月 20, 2021

用C语言实现简单小游戏

1.用c语言实现三子棋。

#define _CRT_SECURE_NO_WARNINGS

#include

#include

#include

#define ROW 3

#define COL 3

char g_broad[ROW][COL];

void Init(char broad[ROW][COL]) {

for (int row = 0; row < ROW; ++row) {

for (int col = 0; col < COL; ++col) {

broad[row][col] = ’ ‘;

}

}

}

void Print(char broad[ROW][COL]) {

for (int row = 0; row < ROW; ++row) {

printf(“| %c | %c | %c |n”,broad[row][0],

broad[row][1],broad[row][2]);

if (row != ROW – 1) {

printf(“—|—|—n”);

}

}

}

void PlayerMove(char broad[ROW][COL]) {

printf(“玩家落子!n”);

while (1) {

int row = 0; int col = 0;

printf(“请输入一组坐标(row col):”);

scanf(“%d %d”,&row,&col);

if (row = ROW || col = COL) {

printf(“您输入的坐标非法,请重新输入!n”);

continue;

}

if (broad[row][col] != ’ ‘) {

printf(“该位置已被占用,请重新输入!n”);

continue;

}

broad[row][col] = ‘x’;

break;

}

}

void ComputerMove(char broad[ROW][COL]) {

printf(“电脑落子!n”);

while (1) {

int row = rand() % ROW;

int col = rand() % COL;

if (broad[row][col] != ‘ ‘) {

//该位置被占用,重新生成随机数!

continue;

}

broad[row][col] = ‘o’;

break;

}

}

int Isfull(char broad[ROW][COL]) {

for (int row = 0; row < ROW; ++row) {

for (int col = 0; col < COL; ++col) {

if (broad[row][col] == ’ ‘) {

return 0;

}

}

}

return 1;

}

char CheckWinner(char broad[ROW][COL]) {

//先检查所有行

for (int row = 0; row < ROW; ++row) {

if (broad[row][0] == broad[row][1]

&& broad[row][0] == broad[row][2]

&& broad[row][0] != ’ ‘) {

return broad[row][0];

}

}

//检查所有列

for (int col = 0; col < COL; ++col) {

if (broad[0][col] == broad[1][col]

&& broad[0][col] == broad[2][col]

&& broad[0][col] != ’ ‘) {

return broad[0][col];

}

}

//检查对角线

if (broad[0][0] == broad[1][1]

&& broad[0][0] == broad[2][2]

&& broad[0][0] != ‘ ‘) {

return broad[0][0];

}

if (broad[2][0] == broad[1][1]

&& broad[2][0] == broad[0][2]

&& broad[2][2] != ‘ ‘) {

return broad[2][0];

}

if (Isfull(broad)) {

return ‘q’;

}return ‘ ‘;

}

void Game() {

//1.先对棋盘进行初始化;

Init(g_broad);

char Winner = ’ ‘;

while (1) {

//2.打印棋盘;

Print(g_broad);

//3.玩家落子,检查游戏是否结束;

PlayerMove(g_broad);

Winner = CheckWinner(g_broad);

if (Winner != ’ ‘) {

break;

}

//4.电脑落子,检查游戏是否结束;

ComputerMove(g_broad);

char Winner = CheckWinner(g_broad);

if (Winner != ’ ‘) {

break;

}

}

Print(g_broad);

if (Winner == ‘x’) {

printf(“玩家胜利!n”);

}

else if (Winner == ‘o’) {

printf(“电脑胜利!n”);

}

else if (Winner == ‘q’) {

printf(“和棋!n”);

}

else {

printf(“程序出错!n”);

}

//5.循环第二步。

}

int Menu() {

printf(“=n”);

printf(“1.开始游戏!n”);

printf(“0.结束游戏!n”);

printf(“=n”);

printf(“请输入您的选择!n”);

int choice;

scanf(“%d”,&choice);

return choice;

}

int main() {

srand((unsigned int)time(0));

while (1) {

int choice = Menu();

if (choice == 1) {

Game();

}

else {

printf(“Good bey!n”);

break;

}

}

return 0;

}

打印出来的棋盘不太好看,你们可以根据自己的想法将棋盘改的好看些!

这个程序主要应用了数组,需要主要的是(eg:if (row = ROW || col = COL)必须加上row >= ROW,这可以保证数组的下标不越界。)还有随机种子的设定只要在程序启动时设置一次就行了。