0

我正在尝试将我用 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
...

在 Java 版本中,我有一个单独的类用于定义 Player 对象,以及游戏的 main 方法。

例如(这是一个小版本):

game.java(返回省略)

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
    };
};

player.java(返回省略)

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
};

假设当两个类编译在一起时,程序将能够运行,因为主变量是公共的,并且播放器变量是在程序进行时定义的。但是,编译器无法识别这一点并引发错误,因为类(顺便说一句,在同一目录中)不会相互读取,并且在检查时未在数组/数组列表中“定义”对象。

你如何让编译器看到定义的变量?如果需要,我可以上传两个类的当前工作版本和最终的 python 版本,但我喜欢让我的游戏保持闭源。

编辑:根据 sjkm 的回复修复 ArrayList 初始化

4

1 回答 1

0

定义列表的通用类型:

改变

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>();

否则,您总是必须投射从列表中获得的对象...

于 2013-09-30T17:01:45.817 回答