洛谷p1838三子棋C语言
时间: 2024-01-14 09:20:06 浏览: 131
C语言版三子棋
三子棋是一种非常经典的棋类游戏,玩家和电脑轮流下棋,先将三个棋子连成一条线的一方获胜。下面是洛谷p1838三子棋C语言的代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROW 3
#define COL 3
void Initboard(char arr[ROW][COL], int row, int col) {
int i, j;
for (i = 0; i < row; i++)
for (j = 0; j < col; j++)
arr[i][j] = ' ';
}
void Displayboard(char arr[ROW][COL], int row, int col) {
int i, j;
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
printf(" %c ", arr[i][j]);
if (j < col - 1)
printf("|");
}
printf("\n");
if (i < row - 1) {
for (j = 0; j < col; j++) {
printf("---");
if (j < col - 1)
printf("|");
}
printf("\n");
}
}
}
void Player_p(char arr[ROW][COL], int row, int col) {
printf("玩家下:>\n");
int i, j;
scanf("%d%d", &i, &j);
while (i > row || i < 1 || j > col || j < 1) {
printf("坐标非法,请重输:\n");
scanf("%d%d", &i, &j);
}
while (arr[j - 1][i - 1] == '#' || arr[j - 1][i - 1] == '*') {
printf("坐标已被占用,请重新输入:\n");
scanf("%d%d", &i, &j);
}
arr[j - 1][i - 1] = '*';
}
void Computer_p(char arr[ROW][COL], int row, int col) {
printf("电脑下:>\n");
int i, j;
srand((unsigned int)time(NULL));
while (1) {
i = rand() % row;
j = rand() % col;
if (arr[i][j] == ' ') {
arr[i][j] = '#';
break;
}
}
}
char Checkwin(char arr[ROW][COL], int row, int col) {
int i;
for (i = 0; i < row; i++) {
if (arr[i][0] == arr[i][1] && arr[i][1] == arr[i][2] && arr[i][0] != ' ')
return arr[i][0];
}
for (i = 0; i < col; i++) {
if (arr[0][i] == arr[1][i] && arr[1][i] == arr[2][i] && arr[0][i] != ' ')
return arr[0][i];
}
if (arr[0][0] == arr[1][1] && arr[1][1] == arr[2][2] && arr[0][0] != ' ')
return arr[0][0];
if (arr[0][2] == arr[1][1] && arr[1][1] == arr[2][0] && arr[0][2] != ' ')
return arr[0][2];
if (i == row && i == col)
return 'q';
return ' ';
}
int main() {
char board[ROW][COL];
char ret;
Initboard(board, ROW, COL);
Displayboard(board, ROW, COL);
while (1) {
Player_p(board, ROW, COL);
Displayboard(board, ROW, COL);
ret = Checkwin(board, ROW, COL);
if (ret != ' ') {
break;
}
Computer_p(board, ROW, COL);
Displayboard(board, ROW, COL);
ret = Checkwin(board, ROW, COL);
if (ret != ' ') {
break;
}
}
if (ret == '*') {
printf("玩家获胜!\n");
}
else if (ret == '#') {
printf("电脑获胜!\n");
}
else {
printf("平局!\n");
}
return 0;
}
```
阅读全文