我是 Java 新手(和一般编程),我正在尝试编写一个可以玩 Go Fish 的程序,但是我很难让一个对象调用另一个对象方法。它还没有完成,但这是我到目前为止所拥有的。这将被称为开始游戏:
public class StartGame {
public static void start(){
Deck deck = new Deck(1);
GoFishHumanPlayer player = new GoFishHumanPlayer();
GoFishAiPlayer ai = new GoFishAiPlayer();
player.drawHand();
ai.drawHand();
player.turn();
}
}
用作游戏牌组的对象。
import java.util.Random;
public class Deck {
private int[] card = new int[14];
private int size;
Random r = new Random();
public Deck(int x){
size = x;
card[0] = 4 * size * 13;
card[1] = 4 * size;
card[2] = 4 * size;
card[3] = 4 * size;
card[4] = 4 * size;
card[5] = 4 * size;
card[6] = 4 * size;
card[7] = 4 * size;
card[8] = 4 * size;
card[9] = 4 * size;
card[10] = 4 * size;
card[11] = 4 * size;
card[12] = 4 * size;
card[13] = 4 * size;}
public int draw(){
int x = r.nextInt(card[0]) + 1;
int y = 1;
while(x>card[y]){
x -=card[y];
y++;}
card[y]--;
card[0]--;
return y;}
}
下一个类将由 GoFishHumanPlayer 和 GoFishAiPlayer 扩展。这些对象将代表玩家。
public class GoFishPlayer {
private int[] hand = new int[14];
private int pairs;
public void drawHand(){
for(int x = 0; x < 5; x++){
int y = deck.draw();//Here's where I get an error "deck cannot be resolved"
hand[y]++;}
}
}
在 GoFishPlayer 的第 8 行,我的 IDE 显示“无法解析甲板”。回到 StartGame,我创建了一个名为 deck 的对象,但是如何让所有类都可以访问它。