2014-11-14 2 views
0

Я был с ошибками наличия такого рода ошибки «первым случайным исключением типа„System.ArgumentNullException“произошел в PresentationFramework.dll»System.ArgumentNullException после нескольких раундов игр

Ok это мой код:

DispatcherTimer timer; 
    int count = 1; 
    bool ball1visibility = true; 
    bool ball2visibility = true; 
    bool ball3visibility = true; 
    bool ball4visibility = true; 
    bool ball5visibility = true; 
    bool gameover = false; 

    int score1 = 0; 
    int score2 = 0; 
    int overallscore1 = 0; 
    int overallscore2 = 0; 
public void militimer_Tick(object sender, EventArgs e) 
    { 
     TimeSpan result = TimeSpan.FromMilliseconds(count++); 

     if (Game != null) 
     { 
      DetectScoring(); 
     } 
    } 
public void ShowGame(Game game) 
    { 
     if (Game == null) 
     { 
      Game = game; 
      arenaContainer.Content = game; 
      Game.SetGameLoop(gameLoop); 
     } 
    } 

    public void Window_Loaded(object sender, RoutedEventArgs e) 
    {    
     Game game = new PlayGame();  
     ShowGame(game); 
     gameLoop.Start(); 
    } 

    void DetectScoring() 
    { 
     if (Game != null && arenaContainer.Content != null && gameover == false) 
     { 

      PlayGame sg = (PlayGame)Game; //class that calls the objects of the game 
      var topball1 = Canvas.GetTop(sg.ellipseBall1); 
      var leftball1 = Canvas.GetLeft(sg.ellipseBall1); 
      Rect ball1rect = new Rect(leftball1, topball1, 18, 18); //basically the balls that should be inside the pocket in order to get points 

      var topball2 = Canvas.GetTop(sg.ellipseBall2); 
      var leftball2 = Canvas.GetLeft(sg.ellipseBall2); 
      Rect ball2rect = new Rect(leftball2, topball2, 18, 18); 

      var topball3 = Canvas.GetTop(sg.ellipseBall3); 
      var leftball3 = Canvas.GetLeft(sg.ellipseBall3); 
      Rect ball3rect = new Rect(leftball3, topball3, 18, 18); 

      var topball4 = Canvas.GetTop(sg.ellipseBall4); 
      var leftball4 = Canvas.GetLeft(sg.ellipseBall4); 
      Rect ball4rect = new Rect(leftball4, topball4, 18, 18); 

      var topball5 = Canvas.GetTop(sg.ellipseBall5); 
      var leftball5 = Canvas.GetLeft(sg.ellipseBall5); 
      Rect ball5rect = new Rect(leftball5, topball5, 18, 18); 


      // player 1 goal/ Player 2 gains points here 
      topLeft.RadiusX = 25/2; 
      topLeft.RadiusY = 25/2; 
      Rect h1rect = topLeft.Bounds; // pocket hole 1 

      botLeft.RadiusX = 25/2; 
      botLeft.RadiusY = 25/2; 
      Rect h2rect = botLeft.Bounds; // pocket hole 2 


      //vice versa 
      topRight.RadiusX = 25/2; 
      topRight.RadiusY = 25/2; 
      Rect h3rect = topRight.Bounds; // pocket hole 3 

      botRight.RadiusX = 25/2; 
      botRight.RadiusY = 25/2; 
      Rect h4rect = botRight.Bounds; // pocket hole 4 


      //check intersection of pocket with the balls 
      if (ball1rect.IntersectsWith(h1rect) || ball1rect.IntersectsWith(h2rect)) 
      { 
       if (ball1visibility == true) 
       { 
        //  Player1Score.Content = "Player 2 score:" + score2; 
        Game.RemoveVisual(sg.ellipseBall1); 
        ball1visibility = false; 
        Console.WriteLine("Player 2 scores ball1"); 
        score2 += 1; 
       } 
      } 

      else if (ball1rect.IntersectsWith(h3rect) || ball1rect.IntersectsWith(h4rect)) 
      { 
       if (ball1visibility == true) 
       { 
        //  Player2Score.Content = "Player 1 scores"; 
        Game.RemoveVisual(sg.ellipseBall1); 
        ball1visibility = false; 
        score1++; 
       } 
      } 

      if (ball2rect.IntersectsWith(h1rect) || ball2rect.IntersectsWith(h2rect)) 
      { 
       if (ball2visibility == true) 
       { 
        //  Player1Score.Content = "Player 2 scores"; 
        Game.RemoveVisual(sg.ellipseBall2); 
        ball2visibility = false; 
        score2++; 
       } 

      } 

      else if (ball2rect.IntersectsWith(h3rect) || ball2rect.IntersectsWith(h4rect)) 
      { 
       if (ball2visibility == true) 
       { 
        // Player2Score.Content = "Player 1 scores"; 
        Game.RemoveVisual(sg.ellipseBall2); 
        ball2visibility = false; 
        score1++; 
       } 
      } 

      if (ball3rect.IntersectsWith(h1rect) || ball3rect.IntersectsWith(h2rect)) 
      { 
       if (ball3visibility == true) 
       { 
        // Player1Score.Content = "Player 2 scores"; 
        Game.RemoveVisual(sg.ellipseBall3); 
        ball3visibility = false; 
        score2++; 
       } 
      } 

      else if (ball3rect.IntersectsWith(h3rect) || ball3rect.IntersectsWith(h4rect)) 
      { 
       if (ball3visibility == true) 
       { 
        // Player2Score.Content = "Player 1 scores"; 
        Game.RemoveVisual(sg.ellipseBall3); 
        ball3visibility = false; 
        score1++; 
       } 
      } 

      if (ball4rect.IntersectsWith(h1rect) || ball4rect.IntersectsWith(h2rect)) 
      { 
       if (ball4visibility == true) 
       { 
        // Player1Score.Content = "Player 2 scores"; 
        Game.RemoveVisual(sg.ellipseBall4); 
        ball4visibility = false; 
        score2++; 
       } 
      } 

      else if (ball4rect.IntersectsWith(h3rect) || ball4rect.IntersectsWith(h4rect)) 
      { 
       if (ball4visibility == true) 
       { 
        // Player2Score.Content = "Player 1 scores"; 
        Game.RemoveVisual(sg.ellipseBall4); 
        ball4visibility = false; 
        score1++; 
       } 
      } 

      if (ball5rect.IntersectsWith(h1rect) || ball5rect.IntersectsWith(h2rect)) 
      { 
       if (ball5visibility == true) 
       { 
        // Player1Score.Content = "Player 2 scores"; 
        Game.RemoveVisual(sg.ellipseBall5); 
        ball5visibility = false; 
        score2++; 
       } 
      } 

      else if (ball5rect.IntersectsWith(h3rect) || ball5rect.IntersectsWith(h4rect)) 
      { 
       if (ball5visibility == true) 
       { 
        //  Player2Score.Content = "Player 1 scores"; 
        Game.RemoveVisual(sg.ellipseBall5); 
        ball5visibility = false; 
        score1++; 
       } 
      }      

     } 
     // after the 5 balls are inside the pocket it will count total score 
     if (score1 + score2 == 5 && gameover == false) 
     { 

      Console.WriteLine("Calculating Score"); 
      Scoring(score1, score2); 

     } 
     lbScore1a.Content = score1.ToString(); 
     lbScore2a.Content = score2.ToString(); 
     lbScore1.Content = overallscore1.ToString() + " - "; 
     lbScore2.Content = overallscore2.ToString() + " - "; 
    } 


    // *************** part where I suspect the problem is ****************** 
    public void Scoring(int player1score, int player2score) 
    { 
     player1score = score1; 
     player2score = score2; 
     Console.WriteLine("Score is " + (score1 + score2)); 
       if (score1 > score2 && gameover == false) 
       { 
        gameover = true; 
        timer.Stop(); 
        militimer.Stop(); 
        gameLoop.Stop(); 
        MessageBoxResult result = MessageBox.Show("Player 1 wins", "Win", MessageBoxButton.OK); 

        if (result == MessageBoxResult.OK) 
        { 
         count = 0; 
         timer.Interval = TimeSpan.FromMilliseconds(Convert.ToDouble(1)); 
         timer.Start(); 
         militimer.Interval = TimeSpan.FromMilliseconds(Convert.ToDouble(1)); 
         militimer.Tick += new EventHandler(militimer_Tick); 
         militimer.Start(); 

         gameover = false;              
         Game = null; 
         arenaContainer.Content = null; 

         Game game = new PlayGame(); 
         ShowGame(game); 
         gameLoop.Start(); 
         score1 = 0; 
         score2 = 0; 

         ball1visibility = true; 
         ball2visibility = true; 
         ball3visibility = true; 
         ball4visibility = true; 
         ball5visibility = true; 

         Console.WriteLine("Game restarting 1"); 
        } 
        overallscore1++; 
       } 

       else if (score1 < score2 && gameover == false) 
       { 
        gameover = true; 
        timer.Stop(); 
        militimer.Stop(); 
        gameLoop.Stop(); 
        MessageBoxResult result = MessageBox.Show("Player 2 wins", "Win", MessageBoxButton.OK); 

        if (result == MessageBoxResult.OK) 
        { 
         count = 0; 
         timer.Interval = TimeSpan.FromMilliseconds(Convert.ToDouble(1)); 
         timer.Start(); 
         militimer.Interval = TimeSpan.FromMilliseconds(Convert.ToDouble(1)); 
         militimer.Tick += new EventHandler(militimer_Tick); 
         militimer.Start(); 

         gameover = false; 
         Game = null; 
         arenaContainer.Content = null; 

         Game game = new PlayGame(); 
         ShowGame(game); 
         gameLoop.Start(); 
         score1 = 0; 
         score2 = 0; 

         ball1visibility = true; 
         ball2visibility = true; 
         ball3visibility = true; 
         ball4visibility = true; 
         ball5visibility = true; 
         Console.WriteLine("Game restarting 2"); 
        } 
        overallscore2++; 
       } 

    } 

выход с текущим WriteLine отладки заключается в следующем:

Calculating Score 
Score is 5 
Game restarting 2 
Calculating Score 
Score is 5 
A first chance exception of type 'System.ArgumentNullException' occurred in PresentationFramework.dll 
Game restarting 1 

что игра должна делать то, что, если все 5 шариков внутри. Он сразу же начнет новый раунд, а также добавит общий балл того, кто победит в предыдущем раунде. Я не уверен в ошибке. Иногда я могу ходить до 7 раундов, минимум, 2 раунда. Если вы считаете, что код, который я вам дал, все еще недостаточно, как вы хотите видеть другие классы. Дайте мне знать, чтобы опубликовать его. Я также поставил «****», по которому, как я думаю, вызывает проблему. Я знаю, что этот пост длинный, но заблаговременно за помощь.

Где я думаю, что проблема:

** // *************** part where I suspect the problem is ****************** 
public void Scoring(int player1score, int player2score) 
{ 
    player1score = score1; 
    player2score = score2; 
    Console.WriteLine("Score is " + (score1 + score2)); 
      if (score1 > score2 && gameover == false) 
      { 
       gameover = true; 
       timer.Stop(); 
       militimer.Stop(); 
       gameLoop.Stop(); 
       MessageBoxResult result = MessageBox.Show("Player 1 wins", "Win", MessageBoxButton.OK); 

       if (result == MessageBoxResult.OK) 
       { 
        count = 0; 
        timer.Interval = TimeSpan.FromMilliseconds(Convert.ToDouble(1)); 
        timer.Start(); 
        militimer.Interval = TimeSpan.FromMilliseconds(Convert.ToDouble(1)); 
        militimer.Tick += new EventHandler(militimer_Tick); 
        militimer.Start(); 

        gameover = false;              
        Game = null; 
        arenaContainer.Content = null; 

        Game game = new PlayGame(); 
        ShowGame(game); 
        gameLoop.Start(); 
        score1 = 0; 
        score2 = 0; 

        ball1visibility = true; 
        ball2visibility = true; 
        ball3visibility = true; 
        ball4visibility = true; 
        ball5visibility = true; 

        Console.WriteLine("Game restarting 1"); 
       } 
       overallscore1++; 
      } 

      else if (score1 < score2 && gameover == false) 
      { 
       gameover = true; 
       timer.Stop(); 
       militimer.Stop(); 
       gameLoop.Stop(); 
       MessageBoxResult result = MessageBox.Show("Player 2 wins", "Win", MessageBoxButton.OK); 

       if (result == MessageBoxResult.OK) 
       { 
        count = 0; 
        timer.Interval = TimeSpan.FromMilliseconds(Convert.ToDouble(1)); 
        timer.Start(); 
        militimer.Interval = TimeSpan.FromMilliseconds(Convert.ToDouble(1)); 
        militimer.Tick += new EventHandler(militimer_Tick); 
        militimer.Start(); 

        gameover = false; 
        Game = null; 
        arenaContainer.Content = null; 

        Game game = new PlayGame(); 
        ShowGame(game); 
        gameLoop.Start(); 
        score1 = 0; 
        score2 = 0; 

        ball1visibility = true; 
        ball2visibility = true; 
        ball3visibility = true; 
        ball4visibility = true; 
        ball5visibility = true; 
        Console.WriteLine("Game restarting 2"); 
       } 
       overallscore2++; 
      } 

}** 
+0

У вас есть большая трассировка стека для исключения? –

+3

Я думаю, что никто не прочитает весь ваш исходный код, попробуйте поместить только те части, которые важны для вашей проблемы, в частности, по крайней мере: на какой строке происходит ваша ошибка? – HimBromBeere

+0

@HimBromBeere Я прочитал полный исходный код;) – EvilFonti

ответ

1

пе, что я вижу это вы добавляете событие в millitimer каждый раз, когда вы начинаете новый раунд. Таким образом, после нескольких раундов вы одновременно запускаете несколько событий, а не одно.

То же проблема, если клещ происходит и EventHandler прыгает в DetectScore у вас есть

if (Game != null && arenaContainer.Content != null && gameover == false) 

Это будет решать, как верно, если срабатывает между

gameover = false;              
Game = null; 

Вы должны удалить событие с помощью

militimer.Tick -= new EventHandler(militimer_Tick); 

Сбросить все ваши игры, такие как gameover и вещи и начать время после этого

militimer.Tick += new EventHandler(militimer_Tick); 
militimer.Start(); 

Это должно решить проблему.

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