【发布时间】:2013-11-17 03:16:00
【问题描述】:
我正在尝试用 C 语言制作一个基本的文本游戏。我正在尝试将设置的字符串与用户输入进行比较,但失败了。我对 C 比较陌生(过去我曾使用过 javascript、php 和 C++)。我确信我做错的事情要么是盲目的简单,要么是我在阅读文档时误解了。
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
int main(void) {
/* Game variables */
bool game_over = false,
is_mage = false,
is_warrior = false;
unsigned int sword_damage = 15,
magic_damage = 10,
magika = 20,
strength = 20,
health = 100,
gold = 20;
char name [20],
type [7],
dest_1 [7],
dest_2 [7],
mage [4],
warrior[7];
/* Make string variables */
memset(dest_1, '\0', sizeof(dest_1));
memset(dest_2, '\0', sizeof(dest_2));
strcpy(mage, "mage");
strcpy(dest_1, mage);
strcpy(warrior, "warrior");
strcpy(dest_2, warrior);
/* Print introduction and set up player */
printf("\t\t\t\tAngrokk\n\t\tCopyright: Benjamin Williams 2013\n\n");
printf("Character name: ");
scanf("%s",name);
printf("\nCharacter type (mage/warrior): ");
scanf("%s",type);
if (strcmp(type, dest_1) == 0) {
is_mage = true;
} else if (strcmp(type, dest_2) == 0) {
is_warrior = true;
} else {
printf("No type available, game shutting down.");
return 0;
}
/* Main game loop */
while (!game_over) {
/* Detect if the character is dead or not */
if (health < 0) {
game_over = true;
}
}
printf("Game over");
return 0;
}
【问题讨论】:
-
while(!game_over)请。 -
注意字符串长度应始终包含“\0”字符的空格。例如,你的法师只有 [4] 长..
-
存储“战士”需要多少个字符。提示:它超过 7。据我所知,这些都应该是
const char varname[] = "string value";,然后你可以扔掉strcpy()。 -
谢谢!我改了。
-
所以我应该把两个长度都增加两倍。制作法师6和战士9?