写出五子棋绘制棋盘和有颜色棋子的C语言代码
时间: 2024-03-12 19:46:43 浏览: 130
以下是五子棋绘制棋盘和有颜色棋子的C语言代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#define BOARD_SIZE 15 // 棋盘大小
#define BLACK 'X' // 黑色棋子
#define WHITE 'O' // 白色棋子
void DrawBoard(char board[][BOARD_SIZE]);
void PutChess(char board[][BOARD_SIZE], int x, int y, char player);
int main()
{
char board[BOARD_SIZE][BOARD_SIZE] = {0}; // 棋盘初始化
DrawBoard(board); // 绘制棋盘
PutChess(board, 7, 7, BLACK); // 在(7,7)处放置一颗黑色棋子
PutChess(board, 6, 6, WHITE); // 在(6,6)处放置一颗白色棋子
DrawBoard(board); // 重新绘制棋盘,显示棋子
return 0;
}
// 绘制棋盘
void DrawBoard(char board[][BOARD_SIZE])
{
system("cls"); // 清屏
// 绘制列号
printf(" ");
for (int i = 0; i < BOARD_SIZE; i++) {
printf("%2d", i + 1);
}
printf("\n");
// 绘制横线和行号及棋子
for (int i = 0; i < BOARD_SIZE; i++) {
printf("%2d", i + 1);
for (int j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] == BLACK) {
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED);
printf(" %c", board[i][j]);
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
}
else if (board[i][j] == WHITE) {
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN);
printf(" %c", board[i][j]);
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
}
else {
printf(" +");
}
}
printf("\n");
}
}
// 放置棋子
void PutChess(char board[][BOARD_SIZE], int x, int y, char player)
{
if (x < 0 || x >= BOARD_SIZE || y < 0 || y >= BOARD_SIZE) {
printf("无效的位置\n");
return;
}
if (board[x][y] == BLACK || board[x][y] == WHITE) {
printf("此处已有棋子\n");
return;
}
board[x][y] = player;
}
```
注意:此代码只是演示如何绘制棋盘和放置棋子,并未实现完整的五子棋游戏逻辑。
阅读全文