![](/img/trans.png)
[英]Performance of separate LINQ2SQL selects with group and join on two indexed tables vs. one combined select
[英]Performance and Ressource usage of two Forms vs. one Form with switch case
我正在编写一个没有幽灵的简单吃豆游戏。 所以只有一个符号作为玩家,一些墙壁和物品。
现在我想选择是自己按方向键玩游戏,还是自动解决。 用户所玩游戏的Form完成。 现在我应该创建一个新表单(使用相同的Paint
事件和Load
事件代码)并仅更改必须更改的内容,还是应该通过 switch case 决定将所有代码放在一个表单中?
我通过 PreviewKeyDown 事件捕获方向并将其保存到字符串变量“方向”。 然后启动一个计时器来减慢玩家的一般移动速度。
private void Game_Form_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
//Unterscheide nach Richtung und kontrolliere ob in dieser Richtung Wand ist
switch (e.KeyCode)
{
case Keys.Up:
if (maze[pos_player_index.Item1, pos_player_index.Item2 - 1] == '#')
{
break;
}
else
{
key = "up";
}
break;
.
.
.
}
//Starte Timer Bewegungsgeschwindigkeit t_move
t_move.Start();
}
然后在 OnTickEvent 中我决定如何处理玩家的符号并检查是否有墙。 然后我为播放器调用刷新。 迷宫本身只在全局绘制事件中,所以它只绘制一次。
void t_move_Tick(object sender, EventArgs e) { //Unterscheiden der Richtung durch Hilfsvariable (exemplarisches Kommentieren einer Möglichkeit) switch (key) {
case "up":
//Setzen des neuen Index
pos_player_index = new Tuple<int, int>(pos_player_index.Item1, pos_player_index.Item2 - 1);
//Überschreiben des Zeichens im Labyrinth durch Leerzeichen -> aufgesammelt
maze[pos_player_index.Item1, pos_player_index.Item2] = ' ';
//Neuzeichnen der Spielfigur
p_player.Refresh();
break;
所以图形和控制的代码是完全不同的。
正如其他人所提到的,复制代码是一个坏主意 - 突然之间,您将不得不两次实施所有更改。
有很多方法可以分离程序中的功能。
目前最简单的方法是让你当前的表单成为一个abstract class PacmanForm
来执行“共享”功能,并有一个class UserPacmanForm : PacmanForm
和一个class RobotPacmanForm : PacmanForm
。
但是我不认为 winforms 设计师那么喜欢抽象类。 如果您希望能够使用设计器,请在尝试之前创建项目的备份。
另一种方法是将公共代码移动到单独的PacmanGame
类,例如具有以下方法:
Form.Load
事件处理程序中的代码Render(Graphics g)
游戏的Render(Graphics g)
方法Move(Direction d)
方法然后,您可以创建两个单独的表单,它们都使用PacmanGame
实例。
附注。 我在回答中没有关注性能,因为性能在这里不是问题。 瓶颈很可能是绘制游戏的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.