我正在尝试将我用 Python 制作的游戏移植到 Java。在 Python 版本中,我将所有方法和变量都放在一个“类”中,玩家是这样的字典:
游戏.py
...
new_player={"name":"","hp":0,...}
players=[]
//to add new player
players.append(new_player.copy())
...
players[0]["name"]="bob"
players[0]["hp"]=50
...
import java.utils.*;
public class game
{
public static ArrayList<player> players = new ArrayList<player>();
public static ArrayList<String> pdead = new ArrayList<String>();
public static int turn = 0;
public static void main(String[] args)
{
//do stuff
players.add(new player(name));
//do other stuff
}
public static void do_move(move)
{
//some move is selected
players.get(turn).set_hp(10);
//at this point compiler throws error: cannot find symbol
//compiler does not recognize that a player should have
//been added to the players variable
//other stuff
};
};
public class player
{
//arbitrary list of private variables like hp and name
public player(new_name)
{
name = new_name;
//other variables defined
};
public void set_hp(int amount) //Adding hp
{
hp += amount;
};
public void set_hp(int amount,String type) //taking damage
{
mana += amount;
//go through types, armor, etc.
hp -= amount;
};
public void display stats() //displays all player's stats before choosing move
{
//display stats until...
//later in some for loop
System.out.println(players.get(index).get_hp());
//here compiler throws error again: cannot find symbol
//players arraylist is in main class's public variables
//other stuff
};
//other stuff
};
最佳答案
定义列表的通用类型:
改变
public static ArrayList players = new ArrayList<player>();
public static ArrayList pdead = new ArrayList<String>();
public static ArrayList<player> players = new ArrayList<player>();
public static ArrayList<String> pdead = new ArrayList<String>();
https://stackoverflow.com/questions/19099622/