2016-11-21 15 views
2

试图循环浏览我的角色,但一旦我点击下一个最后一个角色,它就会打破。 visual studio给出的回应是:ArgumentOutOfRangeException未被处理并引用我的“playerCharacter pc = player [currentPlayerIndex];”VS打破一旦清单过去2(1),而不是循环回0

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 

namespace RPGExample 
{ 
    public partial class Form1 : Form 
    { 

     private List<PlayerCharacter> player; 

     int currentPlayerIndex = 0; 

     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 
      // set up an empty list 
      player = new List<PlayerCharacter>(); 


      // add a couple of players 
      player.Add(new PlayerCharacter("Attila")); 

      player.Add(new PlayerCharacter("Boromir")); 

      // create some weapons (could be in a list too) 
      Weapon sword = new Weapon("Broadsword",40,5); 

      Weapon leatherShield = new Weapon("Leather Shield",2,35); 

      Weapon woodenStaff = new Weapon("Wooden Staff",30,10); 

      // and some food 
      Food bread = new Food("Bread", 15); 

      // because Weapons and food inherit from CollectableObject 
      // a player can carry either (polymorphism) 

      // equip the players 
      player[0].Add(sword); 
      player[0].Add(leatherShield); 

      player[1].Add(woodenStaff); 

      player[1].Add(bread); 


      // display the player we are viewing 
      DisplayPlayer(currentPlayerIndex); 

     } 


     // display info about a player by calling objects to string function 
     public void DisplayPlayer(int playerIndex) 
     { 
      // we number from 1 for the user 
      // try removing the brackets around playerIndex + 1 !!! 
      lblPlayerInfo.Text = "Player " + (playerIndex + 1); 

      PlayerCharacter pc = player[currentPlayerIndex]; 
      txtPlayers.Text = pc.ToString(); 
     } 

     private void btnPrevious_Click(object sender, EventArgs e) 
     { 
      if (currentPlayerIndex > 0) 
      { 
       currentPlayerIndex--; 
       DisplayPlayer(currentPlayerIndex); 
      } 
     } 

     private void btnNext_Click(object sender, EventArgs e) 
     { 
      if (currentPlayerIndex < player.Count) 
      { 
       currentPlayerIndex++; 
       DisplayPlayer(currentPlayerIndex); 
      } 
     } 

    } 
} 
+0

'如果(currentPlayerIndex

回答

0

你应该只DisplayPlayer incremeent /递减currentPlayerIndex之前,或通过用等式(< =):)

private void btnPrevious_Click(object sender, EventArgs e) 
    { 
     if (currentPlayerIndex >= 0) 
     { 
      currentPlayerIndex--; 
      DisplayPlayer(currentPlayerIndex); 
     } 
    } 

    private void btnNext_Click(object sender, EventArgs e) 
    { 
     if (currentPlayerIndex < player.Count) 
     { 
      currentPlayerIndex++; 
      DisplayPlayer(currentPlayerIndex); 
     } 
    }