C#使用队列存储多个2D数组 [英] C# Using A Queue to Store multiple 2D Arrays

查看:141
本文介绍了C#使用队列存储多个2D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在Visual Studio控制台中制作棋盘游戏,我想使用队列在最后播放整个游戏。为此,我确保每次画板时都会排队,以便将该板的实例添加到队列中。

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.

我如何实例化队列:

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);
     }

遇到的问题是队列中仅包含板的实例最终状态,我认为这是因为队列只能包含唯一值,因此当尝试添加到队列时,它将覆盖所有先前值。通过阅读其他示例,建议创建对象的新实例或将原始数据添加到队列中。由于这些与2D数组无关,因此我很难与之联系,是否有一种方法可以解决此问题而又不大幅度改变我的代码流向?

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?

推荐答案


将板放入队列以进行重播时,您需要对其进行克隆。问题在于,当您将板状态放入队列时,实际上是在将指针指向要代表董事会。 – Sumner Evans

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

然后将解决此问题。

这篇关于C#使用队列存储多个2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆