我想將我在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不要求用';'關閉括號{}。 –