2015-05-01 2 views
1

Я создаю очень простую игру pacman как домашнюю работу. Я работаю в Visual Studio, в C#. Проблема в том, что когда я нажимаю run, только winform показывает с ним ничего. Может кто-нибудь сказать мне, что я сделал неправильно?Pacman - как исправить

namespace pacman 
{ 
    public partial class Form1 : Form 
    { 
     Timer timer; 
     Pacman pacman; 
     static readonly int TIMER_INTERVAL = 250; 
     static readonly int WORLD_WIDTH = 15; 
     static readonly int WORLD_HEIGHT = 10; 
     Image foodImage; 
     bool[][] foodWorld; 

     public Form1() 
     { 
      InitializeComponent(); 

      foodImage = Properties.Resources.orange_detoure; 
      DoubleBuffered = true; 
      newGame(); 
     } 

     public void newGame() 
     { 
      pacman = new Pacman(); 
      this.Width = Pacman.radius * 2 * (WORLD_WIDTH + 1); 
      this.Height = Pacman.radius * 2 * (WORLD_HEIGHT + 1); 

      foodWorld = new bool[WORLD_WIDTH][]; 

      timer = new Timer(); 
      timer.Interval = TIMER_INTERVAL; 
      timer.Tick += new EventHandler(timer_Tick); 
      timer.Start(); 
     } 

     void timer_Tick(object sender, EventArgs e) 
     { 
      timer.Interval = TIMER_INTERVAL - 1; 
      if (TIMER_INTERVAL == 0) 
      { 
       timer.Stop(); 
      } 
      pacman.Move(WORLD_WIDTH, WORLD_HEIGHT); 
      Invalidate(); 
     } 

     private void Form1_KeyUp(object sender, KeyEventArgs e) 
     { 
      if (Keys.Up != 0) 
      { 
       pacman.ChangeDirection("UP"); 
      } 
      if (Keys.Down != 0) 
      { 
       pacman.ChangeDirection("DOWN"); 
      } 
      if (Keys.Left != 0) 
      { 
       pacman.ChangeDirection("LEFT"); 
      } 
      if (Keys.Right != 0) 
      { 
       pacman.ChangeDirection("RIGHT"); 
      } 
      Invalidate(); 
     } 

     private void Form1_Paint(object sender, PaintEventArgs e) 
     { 
      Graphics g = e.Graphics; 
      g.Clear(Color.White); 
      for (int i = 0; i < foodWorld.Length; i++) 
      { 
       for (int j = 0; j < foodWorld[i].Length; j++) 
       { 
        if (foodWorld[i][j]) 
        { 
         g.DrawImageUnscaled(foodImage, j * Pacman.radius * 2 + (Pacman.radius * 2 - foodImage.Height)/2, i * Pacman.radius * 2 + (Pacman.radius * 2 - foodImage.Width)/2); 
        } 
       } 
      } 
      pacman.Draw(g); 
     } 
    } 
} 

А вот класс Pacman:

namespace pacman 
{ 
    public class Pacman 
    { 
     public enum dir {UP, DOWN, RIGHT, LEFT}; 

     public float x { get; set; } 
     public float y { get; set; } 
     public string direction { get; set; } 
     static public int radius = 20; 
     public double speed { get; set; } 
     public bool open { get; set; } 
     public Brush brush = new SolidBrush(Color.Yellow); 

     public Pacman() { 
      this.x = 7; 
      this.y = 5; 
      this.speed = 20; 
      this.direction = Convert.ToString(dir.RIGHT); 
      this.open = false; 
     } 

     public void ChangeDirection(string direct) 
     { 
      // vasiot kod ovde 
      for (int i = 0; i < 3; i++) { 

       if(direct == Convert.ToString(dir.RIGHT)) 
       { 
        direction = "RIGHT"; 
       } 
       if (direct == Convert.ToString(dir.LEFT)) 
       { 
        direction = "LEFT"; 
       } 
       if (direct == Convert.ToString(dir.UP)) 
       { 
        direction = "UP"; 
       } 
       if (direct == Convert.ToString(dir.DOWN)) 
       { 
        direction = "DOWN"; 
       } 
      } 
     } 

     public void Move(float width, float height) 
     { 
      if (direction == Convert.ToString(dir.RIGHT)) 
      { 
       x = x + 1; 
       if (x > width) { 
        x = 1; 
       } 
      } 
      else if (direction == Convert.ToString(dir.LEFT)) 
      { 
       x = x - 1; 
       if (x < 0) { 
        x = 14; 
       } 
      } 
      else if (direction == Convert.ToString(dir.UP)) 
      { 
       y = y + 1; 
       if (y > height) { 
        y = 1; 
       } 
      } 
      else if (direction == Convert.ToString(dir.DOWN)) 
      { 
       y = y - 1; 
       if (y < 0) { 
        y = 14; 
       } 
      } 
     } 

     public void Draw(Graphics g) 
     { 
      if (!open) { 
       g.FillEllipse(brush, 7, 5, 15, 15); 
      } 
     } 
    } 
} 

Он должен выглядеть следующим образом http://prntscr.com/70e0jt. Я буду признателен, если кто-то может сказать мне, что я должен исправить, так что, наконец, работает ..

+1

После быстрого чтения ..... вы никогда не вызываете метод 'Form1_Paint' ... – Sidewinder94

+1

Действительно' Form1_Paint' должен быть вызван или код, помещенный в защищенное 'OnPaint' переопределение базы форма. Я думаю, что OP может иметь неправильное переопределение или пропустить создание обработчика события Paint в конструкторе. –

+0

Я проверил и зафиксировал это, но теперь отображается только белый фон. Ничего больше. –

ответ

2

Добавить это в конструкторе:

this.Paint += Form1_Paint;

Что происходит, что вы сделали обработчик Paint, но никогда не назначал событие рисования для его обработки (что я вижу, возможно, что событие было назначено в другой частичной части класса).

Другая проблема заключается в том, что вы не полностью определили переменную «пищевой мир», вы инициализировали первый ранг, но не второй. Вам нужно полностью инициализировать это и установить в нем булевы.

Смежные вопросы