用C语言写五子棋游戏能用vs运行的
时间: 2023-05-28 11:05:35 浏览: 145
五子棋C语言有源码已运行vs写的
以下为C语言实现五子棋游戏的示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#define ROW 15
#define COL 15
void gotoxy(int x, int y) {
COORD c;
c.X = x;
c.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), c);
}
void draw_board() {
int i, j;
printf("\n\n");
for (i = 0; i < ROW; i++) {
gotoxy(20, i + 2);
for (j = 0; j < COL; j++) {
if (i == 0 && j == 0)
printf("┌");
else if (i == 0 && j == COL - 1)
printf("┐");
else if (i == ROW - 1 && j == 0)
printf("└");
else if (i == ROW - 1 && j == COL - 1)
printf("┘");
else if (i == 0 || i == ROW - 1)
printf("─");
else if (j == 0 || j == COL - 1)
printf("│");
else
printf("┼");
}
}
}
void print_piece(int x, int y, int player) {
gotoxy(y * 2 + 20, x + 2);
if (player == 1)
printf("●");
else
printf("○");
}
int check_win(int board[][COL], int x, int y, int player) {
int i, j;
int count = 0;
// check row
for (i = y - 4; i <= y; i++) {
if (i < 0 || i + 4 >= COL)
continue;
count = 0;
for (j = i; j <= i + 4; j++) {
if (board[x][j] == player)
count++;
else
break;
}
if (count == 5)
return 1;
}
// check column
for (i = x - 4; i <= x; i++) {
if (i < 0 || i + 4 >= ROW)
continue;
count = 0;
for (j = i; j <= i + 4; j++) {
if (board[j][y] == player)
count++;
else
break;
}
if (count == 5)
return 1;
}
// check diagonal
for (i = x - 4; i <= x; i++) {
if (i < 0 || i + 4 >= ROW)
continue;
count = 0;
for (j = 0; j < 5; j++) {
if (board[i+j][y+i-j] == player)
count++;
else
break;
}
if (count == 5)
return 1;
}
// check anti-diagonal
for (i = x - 4; i <= x; i++) {
if (i < 0 || i + 4 >= ROW || y + 4 >= COL)
continue;
count = 0;
for (j = 0; j < 5; j++) {
if (board[i+j][y-j] == player)
count++;
else
break;
}
if (count == 5)
return 1;
}
return 0;
}
int main() {
int board[ROW][COL] = {0};
int player = 1;
int x, y;
draw_board();
while (1) {
printf("\nPlayer %d's turn: ", player);
scanf("%d%d", &x, &y);
if (x < 1 || x > 15 || y < 1 || y > 15) {
printf("Invalid input! Please enter again.\n");
continue;
}
if (board[x-1][y-1] != 0) {
printf("The position has been taken! Please choose another one.\n");
continue;
}
board[x-1][y-1] = player;
print_piece(x-1, y-1, player);
if (check_win(board, x-1, y-1, player)) {
printf("\nPlayer %d wins!\n", player);
break;
}
player = player == 1 ? 2 : 1;
}
return 0;
}
```
该程序使用了头文件 `<windows.h>` 和函数 `SetConsoleCursorPosition()` 来实现光标移动和清屏功能,因此需要在 Windows 系统下编译和运行。在 Visual Studio 中,可以使用以下步骤运行该程序:
1. 创建一个新的控制台应用程序项目。
2. 将上述代码复制到“main.c”文件中。
3. 在菜单栏中选择“生成”->“生成解决方案”来编译程序。
4. 点击“本地 Windows 调试器”按钮或按下“F5”键来运行程序。
运行程序后,程序将在控制台中显示出一个五子棋棋盘,玩家可以通过输入坐标来下棋,并且程序会判断是否有玩家获胜。
阅读全文