我刚刚开始学习链接列表,我正在尝试创建一个带有几个节点的小游戏。我已经创建了7个节点,我正在尝试创建一个小游戏,我可以从节点到节点,直到用户逃离我的城堡..我的游戏开始工作良好,第二级也是如此,但一旦我到达第三级无论我选择什么,我都会得到NULL。这是我第一次创建这样的小程序,所以任何修复问题的提示都会非常感激。到目前为止,这是我的代码......
#include <iostream>
#include <string>
using namespace std;
struct ListNode
{
string text1;
string text2;
string text3;
string text4;
ListNode *right;
ListNode *left;
ListNode *up;
ListNode *down;
int choice;
ListNode()
{
text1 = "NULL";
text2 = "NULL";
text3= "NULL";
text4= "NULL";
right = NULL;
left = NULL;
up = NULL;
down = NULL;
choice = 1;
}
};
int main()
{
char choice;
ListNode *start = new ListNode();
ListNode *two = NULL;
two = new ListNode();
start->right = two;
two->left = start;
ListNode *three = NULL;
three = new ListNode();
two->down = three;
three->up = two;
ListNode *four = NULL;
four = new ListNode();
four->right = four;
three->left = three;
ListNode *five = NULL;
five = new ListNode();
five->right = five;
three->left = four;
ListNode *six = NULL;
six = new ListNode();
six->up = six;
five->down = five;
ListNode *seven = NULL;
seven = new ListNode();
seven->up = seven;
three->down = six;
start->text1 = "Welcome to my Castle.";
start->text2 = "You cannot leave!!";
two->text1 = "yay i'm in the second level!";
two->text2 = "Oh no, i'm at the second level again?";
three->text1= "yay, im on the third level";
three->text2= "Oh no, i'm at the third level again?";
four->text1= "yay, im on the fourth level";
four->text2= "Oh no, i'm at the fourth level again?";
five->text1= "yay, im on the fifth level";
five->text2= "Oh no, i'm at the fifth level again?";
six->text1= "yay, im on the sixth level";
six->text2= "Oh no, i'm at the sixth level again?";
seven->text1= "yay, im on the seventh level and have ESCAPED the castle";
seven->text2= "Oh no, i'm at the seventh level again?";
ListNode *ptr = start;
while (true)
{
if (ptr->choice == 1)
{
cout<<ptr->text1<<endl;
ptr->choice = 2;
}
else
cout<<ptr->text2<<endl;
if (ptr->up != NULL)
{
cout<<"Press w to go up"<<endl;
}
if (ptr->down != NULL)
{
cout<<"Press s to go down"<<endl;
}
if (ptr->left != NULL)
{
cout<<"Press a to go left"<<endl;
}
if (ptr->right != NULL)
{
cout<<"Press d to go right"<<endl;
}
cin>>choice;
if (choice == 'w')
ptr = ptr->up;
else if (choice == 's')
ptr = ptr->down;
else if (choice == 'a')
ptr = ptr->left;
else if (choice == 'd')
ptr = ptr->right;
else
{
cout<<"wrong input.. "<<choice<<" was not an option"<<endl;
}
}
return 0;
}
答案 0 :(得分:2)
但是一旦我到达第三级并向左移动,我的程序会显示单词NULL并在我身上崩溃
代码中没有任何地方打印text3
或text4
。因此......
three->text3= "yay, im on the third level";
three->text4= "Oh no, i'm at the second level again?";
应该是这个......
three->text1= "yay, im on the third level";
three->text2= "Oh no, i'm at the second level again?";