private void GhostMove(Ghost ghost) { int direction = Direction(ghost); Invalidate(ghost.GetFrame()); // Moves the ghost based on the direction given by the Direction method switch (direction) { case 1: { if (CanGhostMove(Side.left, ghost)) { ghost.MoveLeft(ClientRectangle); } Invalidate(ghost.GetFrame()); break; } case 2: { if (CanGhostMove(Side.right, ghost)) { ghost.MoveRight(ClientRectangle); } Invalidate(ghost.GetFrame()); break; } case 3: { if (CanGhostMove(Side.bottom, ghost)) { ghost.MoveDown(ClientRectangle); } Invalidate(ghost.GetFrame()); break; } case 4: { if (CanGhostMove(Side.top, ghost)) { ghost.MoveUp(ClientRectangle); } Invalidate(ghost.GetFrame()); break; } default: break; } }
private bool CanGhostMove(Side aSide, Ghost ghost) { int theSide = (int)aSide; Cell GhostCell = TheMaze.GetCellFromPoint(ghost.Position.X + 10, ghost.Position.Y + 10); if (GhostCell.Walls[theSide] == 1) { if (GhostCell.GetWallRect((int)aSide).IntersectsWith(ghost.GetFrame())) { return false; // blocked } } return true; }
/* The Direction method gives each ghost a direction every time the GhostMove method is called.*/ private int Direction(Ghost ghost) { int direction = RandomDirection(1, 4); if (CanGhostMove(Side.left, ghost) && ghost.prevDirection == 1) direction = 1; else { if (!CanGhostMove(Side.left, ghost) && ghost.prevDirection == 1) { if (!CanGhostMove(Side.top, ghost)) { if (CanGhostMove(Side.bottom, ghost)) direction = 3; else direction = 2; } else direction = 4; } } if (CanGhostMove(Side.right, ghost) && ghost.prevDirection == 2) direction = 2; else { if (!CanGhostMove(Side.right, ghost) && ghost.prevDirection == 2) { if (!CanGhostMove(Side.top, ghost)) { if (CanGhostMove(Side.bottom, ghost)) direction = 3; else direction = 1; } else direction = 4; } } if (CanGhostMove(Side.bottom, ghost) && ghost.prevDirection == 3) direction = 3; else { if (!CanGhostMove(Side.bottom, ghost) && ghost.prevDirection == 3) { if (!CanGhostMove(Side.right, ghost)) { if (CanGhostMove(Side.left, ghost)) direction = 1; else direction = 4; } else direction = 2; } } if (CanGhostMove(Side.top, ghost) && ghost.prevDirection == 4) direction = 4; else { if (!CanGhostMove(Side.top, ghost) && ghost.prevDirection == 4) { if (!CanGhostMove(Side.right, ghost)) { if (CanGhostMove(Side.left, ghost)) direction = 1; else direction = 3; } else direction = 2; } } ghost.prevDirection = direction; // Keep track of the previous direction of each ghost return direction; }
/* Checks if the ghost bumped into pacman If it did, then the game ends. */ public void CheckGhost(Ghost ghost) { if (m_bGameDone == false) { if (TheEater.GetFrame().IntersectsWith(ghost.GetFrame())) { timer1.Stop(); PlaySoundInThread("pacman_dies.wav"); m_bGameDone = true; int dotsEaten = NumberOfStones - Stones.Count; MessageBox.Show("Game Over\nDots Eaten: " + dotsEaten); LogScore(dotsEaten); DisplayScores(); Invalidate(TheStatusMessage.GetFrame()); Application.Exit(); } } }