三子棋的实现
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include <stdlib.h>
#include <windows.h>
void init(char arr[][3], int x, int y)
{
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
arr[i][j] = ' ';
}
}
return;
}
void face(char arr[][3], int x, int y)
{
for (int i = 0; i < x; i++)
{
if (i > 0)
printf(" -----------------\n");
else
printf("\n");
for (int j = 0; j < y; j++)
{
if (j == 0)
{
printf(" ");
}
printf(" %c ", arr[i][j]);
if (j < 2)
{
printf("|");
}
}
printf("\n");
}
return;
}
int is_legal_pos(char arr[][3], int x, int y)
{
if (x > 3 || x < 1 || y > 3 || y < 1)
{
printf("坐标超范围,请重新输入!\n");
return 1;
}
else;
if (arr[--x][--y] != ' ')
{
printf("该位置被占用,请重新输入!\n");
return 1;
}
else;
return 0;
}
void Go(char arr[][3], int x, int y, char logo)
{
arr[--x][--y] = logo;
system("cls");
face(arr, 3, 3);
}
int is_win(char arr[][3], char logo)
{
for (int i = 0; i < 3; i++)
{
if ((arr[i][0] == logo) && (arr[i][1] == logo) && (arr[i][2] == logo))
{
return 1;
}
if ((arr[0][i] == logo) && (arr[1][i] == logo) && (arr[2][i] == logo))
{
return 1;
}
}
if ((arr[0][0] == logo) && (arr[1][1] == logo) && (arr[2][2] == logo))
{
return 1;
}
if ((arr[2][0] == logo) && (arr[1][1] == logo) && (arr[0][2] == logo))
{
return 1;
}
return 0;
}
void start(char arr[][3])
{
int count = 0;
while (1)
{
printf("\n\n========================================\n\n");
printf(" 横纵坐标范围均为(1~3)\n");
printf(" 指定坐标 > ");
int x, y;
do {
scanf("%d %d", &x, &y);
} while (is_legal_pos(arr, x, y));
Go(arr, x, y, 'X');
count++;
if (is_win(arr, 'X'))
{
printf("\n========================================\n\n\n 你胜利啦!!\n\n 游戏结束\n\n\n");
break;
}
if (count == 9)
{
printf("\n========================================\n\n\n 双方平局!!\n\n 游戏结束\n\n\n");
break;
}
Sleep(1000);
int i, j;
srand(time(NULL));
do {
i = rand() % 3 + 1;
j = rand() % 3 + 1;
} while (is_legal_pos(arr, i, j));
Go(arr, i ,j, '0');
count++;
if (is_win(arr, '0'))
{
printf("\n========================================\n\n\n 电脑胜利!!\n\n 游戏结束\n\n\n");
break;
}
}
return 0;
}
void main()
{
system("title 三子棋");
system("mode con cols=40 lines=30");
while (1)
{
char arr[3][3];
init(arr, 3, 3);
face(arr, 3, 3);
start(arr);
printf("\n========================================\n\n");
printf(" 再来一局(Y/N):\n ");
char i;
scanf(" %c", &i);
if (i == 'N')
break;
else
{
system("cls");
continue;
}
}
return;
}
|