问题
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