我想将我在Python中创建的游戏移植到Java。在Python版本,我曾在一个“类”中的所有方法和变量和球员都像这样一本字典:在其他类中访问主类中的公共变量
game.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对象以及游戏的主要方法。
例如(这是小版本):
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的初始化
Java不要求用';'关闭括号{}。 –