【发布时间】:2015-12-27 02:45:07
【问题描述】:
我正在尝试用 x 标记他们的位置来跟踪玩家的位置。当玩家输入一个字符串时,我相应地增加坐标。但是,当玩家位于距离边界一格的位置,然后尝试移动到地图边缘时,玩家就会消失。
例子:
.....
...x.
.....
.....
.....
玩家位于'x'
如果玩家输入字符串“right”并且我移动player_loc,则数组简单地返回:
.....
.....
.....
.....
.....
我试图通过增加数组的大小来添加一种缓冲区。没有运气。我已经坚持了将近一个星期了。任何帮助,将不胜感激。我为混乱的代码道歉。我在这方面完全是新手,我真的只是在黑暗中摸索所有这些东西。我在这里的论坛上对此进行了研究,但没有找到解决方案。如果您知道我可能(可能)错过的某些事情,请随时指出我的方向。
#include <stdio.h>
#include <string.h>
char map[6][6];
char player_loc = 'x';
int row;
int col;
void init_map()
{
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
map[i][j] = '.';
}
}
}
void print_map()
{
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
printf("%c", map[i][j]);
}
printf("\n");
}
}
int get_player_loc()
{
for (int j = 0; j < 5; j++) {
for (int k = 0; k < 5; k++) {
if(map[j][k] == player_loc)
{
row = k;
col = j;
}
}
}
return row;
return col;
}
void init_player_loc()
{
int check = 1;
for (int g = 0; g < 5; g++) {
for (int h = 0; h < 5; h++) {
if (map[g][h] == 'x') {
check = 0;
}
}
}
if(check == 1) {
map[0][0] = player_loc;
} else {
get_player_loc();
}
}
void move_left()
{
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (map[i][j] == player_loc) {
map[i][j-1] = player_loc;
map[i][j] = '.';
}
}
}
}
void move_right()
{
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (map[i][j] == player_loc) {
map[i][j+1] = player_loc;
map[i][j] = '.';
}
}
}
}
int main(int argc, char* argv[])
{
char input[15];
printf("You enter a room...you can go left, right, or straight. Which way do you go?\n");
int done = 0;
init_map();
map[3][3] = player_loc;
//init_player_loc();
print_map();
while (!done) {
scanf("%s", input);
if (strcmp("left", input) == 0) {
move_left();
printf("You go left...\n");
print_map();
get_player_loc();
printf("%d %d\n", row, col);
done = 1;
}
else if (strcmp("right", input) == 0) {
move_right();
printf("You go right...\n");
print_map();
get_player_loc();
printf("%d %d\n", row, col);
done = 1;
}
else if (strcmp("straight", input) == 0) {
printf("You go straight...");
done = 1;
}
else {
printf("Sorry, can't do that.\n");
}
}
}
【问题讨论】:
-
你在哪里增加索引?
-
抱歉,没有意识到我粘贴了旧文件。解决了这个问题。在 if 语句中,我正在打印坐标以尝试调试它。实际上不是“游戏”的一部分。
-
在
get_player_loc()中,您不能让return row; return col; }返回行和列;它返回单个值,即row—return col;语句不可访问,编译器应对此发出警告。但是,如果您正在设置全局变量,则不需要返回任何一个值;get_player_loc()应该是void get_player_loc(void)最后没有返回。或者你可以从if中返回,如果你到达最后会出现错误;这将显示一个问题(没有玩家)。