紅方:播放器圖片框;
藍色方塊:終點;
黑方:墻;
我在 PictureBox 中組織了一個迷宮。
如果玩家到達到達點,
我想實作一個重放功能,顯示他們再次找到的路徑,我該怎么辦?

public void CreateNewMaze()
{
mazeTiles = new PictureBox[XTILES, YTILES];
for (int i = 0; i < XTILES; i )
{
for (int j = 0; j < YTILES; j )
{
mazeTiles[i, j] = new PictureBox();
int xPosition = (i * TILESIZE) 25;
int yPosition = (j * TILESIZE) 10;
mazeTiles[i, j].SetBounds(xPosition, yPosition, TILESIZE, TILESIZE);
this.Controls.Add(mazeTiles[i, j]);
}
}
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
int directionX = 0;
int directionY = 0;
switch (keyData)
{
case Keys.Left: directionX = -1;
EndGame();
break;
case Keys.Right: directionX = 1;
EndGame();
break;
case Keys.Up: directionY = -1;
EndGame();
break;
case Keys.Down: directionY = 1;
EndGame();
break;
default: return base.ProcessCmdKey(ref msg, keyData);
}
int x = directionX (PlayerPictureBox.Left - 25) / TILESIZE;
int y = directionY (PlayerPictureBox.Top - 10) / TILESIZE;
bool isRoad = mazeTiles[x, y].BackColor != Color.Black;
if (isRoad)
{
PlayerPictureBox.Left = directionX * TILESIZE;
PlayerPictureBox.Top = directionY * TILESIZE;
}
return true;
}
uj5u.com熱心網友回復:
- 將每個步驟(或移動)添加到步驟串列中。
- 添加 Replay 方法,該方法從該串列中獲取每個步驟,執行它,然后等待一段時間。
- 在每場比賽之前清除“步驟”串列(例如在 CreateNewMaze 中)。
- 例如,按空格鍵開始播放。
因此,將此代碼添加到您的表單中:
class Step
{
public int dx;
public int dy;
}
List<Step> steps = new List<Step>();
async void Replay(int delay = 50)
{
int firstX = 1; // Initial player position, maybe you'll have to change it
int firstY = 1;
PlayerPictureBox.Left = 25 firstX * TILESIZE;
PlayerPictureBox.Top = 10 firstY * TILESIZE;
var copy = steps.ToArray(); // Let's make a copy of steps array, to avoid possible conflicts with working array.
foreach (var step in copy)
{
PlayerPictureBox.Left = step.dx * TILESIZE;
PlayerPictureBox.Top = step.dy * TILESIZE;
await Task.Delay(delay);
}
}
像這樣修改 CreateNewMaze:
public void CreateNewMaze()
{
// Add the following line
steps.Clear();
maze = new bool[XTILES, YTILES];
//...
像這樣修改 ProcessCmdKey:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
int directionX = 0;
int directionY = 0;
switch (keyData)
{
// Add the following:
case Keys.Space:
Replay();
return true;
// ...
和下面這樣:
// ...
if (isRoad)
{
// Add the following line
steps.Add(new Step { dx = dx, dy = dy });
PlayerPictureBox.Left = directionX * TILESIZE;
PlayerPictureBox.Top = directionY * TILESIZE;
}
我建議使用不同的 PictureBox 實體來回放這些步驟,以便用戶可以在回放運行時繼續播放。但我會把它留給你。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/517679.html
標籤:C#表格迷宫重播
