[英]Drawing a game board in C
好吧,正如標題所述,我正在嘗試繪制游戲板。 好吧,我自己做的董事會,看起來像他:
4 |
3 |
2 |
1 |
0 |
- - - - -
0 1 2 3 4
但這不是問題。 我很難找到的是我想在板上繪制星形(*)的圖標,並且坐標以這樣的數組給出
posX {2,4,2,1}
posY {2,3,4,4}
所以在這種情況下,我應該在坐標(2,2),(4,3),(2,4),(1,4)等中繪制*。 有任何想法嗎?
如果要在終端(控制台)上打印它們,則不能簡單地打印坐標軸和返回並放置坐標,但是,如果坐標系足夠小,則每次重新繪制整個電路板都不會有問題添加了一個新點。
一種簡單的方法是保留char的二維數組,並根據坐標放置“”或“ *”。 這樣,每次將新點添加到坐標時,您都可以簡單地逐行打印2D數組。
當然,您還負責打印軸,但是該部分應該是直的。
char points [4][4] ={
{' ',' ',' ',' '},
{' ',' ',' ',' '},
{' ',' ',' ',' '},
{' ',' ',' ',' '},
};
這是您將擁有的空白板。 現在,如果您想在坐標(1,2)處輸入內容,您要做的就是說points[1][2]='*';
要打印整個數組,您將需要一個嵌套循環,外部循環遍歷行,內部循環遍歷列。 像這樣的東西:
int i,j;
for (i=0; i<4; ++i)
{
for (j=0; j<4; ++j) printf("%c ", points[i][j]);
printf("\n");
}
這樣,坐標值將從左到右,從上到下增加。 如果需要,則應更改for循環范圍。
要刷新屏幕,我建議您打印一堆換行符以有效地清除屏幕。 還有其他方法可以做到這一點(例如system(“ cls”)),但並非沒有痛苦
這說明了我在評論中的意思,也許有幫助。 在打印之前,它會准備代表游戲板的字符串數組。
#include <stdio.h>
#include <stdlib.h>
#define BOARDX 5
#define BOARDY 5
#define BOARDW (BOARDX*2) // length of text line
char board [BOARDY][BOARDW+1]; // allow for string terminator
void print_board(void)
{
int y, x;
for(y=BOARDY-1; y>=0; y--) {
printf("%-2d|%s\n", y, board[y]);
}
printf(" ");
for(x=0; x<BOARDX; x++)
printf(" -");
printf("\n");
printf(" ");
for(x=0; x<BOARDX; x++)
printf("%2d", x);
printf("\n");
}
void empty_board(void)
{
int y, x;
for(y=0; y<BOARDY; y++) {
for(x=0; x<BOARDW; x++) {
board[y][x] = ' ';
}
board[y][x] = '\0';
}
}
void poke_board(int x, int y, char c)
{
if (y >= 0 && y < BOARDY && x >= 0 && x < BOARDX)
board[y][x*2+1] = c; // correctly spaced
}
int main(void)
{
int posX[]= {2,4,2,1};
int posY[]= {2,3,4,4};
int len = sizeof(posX) / sizeof(posX[0]);
int n;
empty_board();
for(n=0; n<len; n++) {
poke_board(posX[n], posY[n], '*');
}
print_board();
return 0;
}
程序輸出:
4 | * *
3 | *
2 | *
1 |
0 |
- - - - -
0 1 2 3 4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.