c - 基于 C 控制台的 Tic Tac Toc 游戏中的间距问题
问题描述
我在控制台中打印井字游戏时遇到问题,今天开始制作,(实际上我刚开始),我创建了一个显示棋盘的函数,drawBoard()函数,但是当我使用 playerMove() 函数,实际打印板的一个单元格中的 X 时,它会打印它,但它会在它之后隔开所有内容,所以它基本上隔开该行中的每一列,破坏表格。例如,如果将 x 放在第一个单元格中,则该行中的所有内容都会移动 1 个空格。
这是我现在写的:
#include <stdio.h>
void drawBoard();
void start();
void playerMove();
void computerMove();
char trisBoard[3][3];
short computerPoint;
short playerPoint;
short playerRow;
short playerColumn;
int main() {
start();
return 0;
}
void drawBoard()
{
printf("\n");
printf(" Tris Game\n");
printf("\n");
printf(" %c | %c | %c", trisBoard[0][0], trisBoard[0][1], trisBoard[0][2]);
printf("\n----|----|---- \n");
printf(" %c | %c | %c", trisBoard[1][0], trisBoard[1][1], trisBoard[1][2]);
printf("\n----|----|----");
printf("\n %c | %c | %c \n", trisBoard[2][0], trisBoard[2][1], trisBoard[2][2]);
printf("\n");
}
void start()
{
for(int x = 0; x < 9; x++) {
drawBoard();
playerMove();
}
}
void playerMove()
{
printf("It's your turn, where do you wanna instert the X ? \n");
printf("Insert the row (first number is 0) \n");
scanf("%d", &playerRow);
printf("Insert a column (first number is 0) \n");
scanf("%d", &playerColumn);
trisBoard[playerRow][playerColumn] = 'x';
}
谢谢大家 :)
解决方案
用空格而不是空字符初始化板。
// char trisBoard[3][3];
char trisBoard[3][3] = {{' ',' ',' '},{' ',' ',' '},{' ',' ',' '}};
或 in start()
,如果游戏重新开始,这会有所帮助。
memcpy(trisBoard, ' ', sizeof trisBoard);
您还需要更改drawBoard
函数以适应trisBoard
. printf
是行缓冲的,所以一般来说,建议将新行放在字符串的末尾而不是开头。IMO,即使您每方使用 3 个字符,前面有一个空格,x 或 o,后面有一个空格,事情也会更多:
void drawBoard()
{
printf("\n");
printf(" Tris Game\n");
printf("\n");
// the vertical bars don't line up now, but they will when the board
// prints because %c will be replaced by one char.
printf(" %c | %c | %c\n", trisBoard[0][0], trisBoard[0][1], trisBoard[0][2]);
printf("---|---|---\n");
printf(" %c | %c | %c\n", trisBoard[1][0], trisBoard[1][1], trisBoard[1][2]);
printf("---|---|---\n");
printf(" %c | %c | %c\n", trisBoard[2][0], trisBoard[2][1], trisBoard[2][2]);
printf("\n");
}
推荐阅读
- outlook-web-addins - NuGet Office js 与 CDN Office js 不同(旧)
- javascript - 从 CFC 查询结果填充 HTML 表数据
- sql - T-SQL 中的子查询分组
- mysql - 带有附加条件的左连接的mysql计数
- python-3.x - 在集群/网格上分发 python for 循环
- file - 如何在我的本地系统上运行 magento 服务器代码?
- c++ - 为什么不进行交换?
- javascript - 使用JS将2个表单字段一起添加
- regex - 如何在文件中搜索包含点的字符串?
- python - 如何在 Python 中实现 Windows 10 IVirtualDesktopManager 接口?