C ++小链表游戏不断崩溃

c++ small linked list game keeps crashing

本文关键字:崩溃 游戏 链表      更新时间:2023-10-16

我刚刚开始学习链表,我正在尝试创建一个包含几个节点的小游戏。我已经创建了 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;
 }

但是一旦我到达第三级并向左走,我的程序就会显示 NULL 一词并崩溃。

代码中没有任何地方text3text4打印。因此...

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?";