C# Using A Queue to Store multiple 2D Arrays

荒凉一梦 提交于 2019-12-08 09:01:50

问题


I am currently making a board game in visual studio console where I would like to replay the entire game at the end using a queue. To do this I have made sure to enqueue every time I draw my board so the instance of that board is added to the queue.

How I instantiate the queue:

Queue replay = new Queue();

The code used every time I update the board:

draw.UpdateBoard(board);
replay.Enqueue(board);

The code used to display all the instances of the board at the end:

foreach (int[,] q in replay)
     {
           draw.UpdateBoard(q);
           System.Threading.Thread.Sleep(1000);
     }

The problem am encountering is that the queue contains only instances of the board in it's final state, I think this is because the queue can only contain unique values so when trying to add onto the queue it is overriding all the prior values. From reading other examples there are suggestions for creating new instances of the object or adding the raw data to the queue instead. As these were not relating to 2D arrays it was hard for me to relate to, is there a way to fix this problem without largely changing how my code flows?


回答1:


"You need to clone the board when you enqueue it to replay. The problem is that when you enqueue a board state, you are actually enqueuing a pointer to the data that represents the board." – Sumner Evans

replay.Enqueue(board.Clone);

Will then fix the issue.



来源:https://stackoverflow.com/questions/47113135/c-sharp-using-a-queue-to-store-multiple-2d-arrays

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!