2014-12-07 77 views
0

我正在尝试放置一个游戏,但是,我不确定如何解决重置功能。我已经完成了游戏重置的工作,但是,在游戏重新启动时,这个标签应该显示玩家玩过的游戏的数量不会从0改变为0.这是我迄今为止所做的。java重置游戏方法,玩过的游戏数量不增加

显示和标签的定位...

private int noGamesPlayed; 
private JLabel gamesPlayed = new JLabel("Games Played = " + noGamesPlayed); 
getContentPane().add(gamesPlayed); 
gamesPlayed.setBounds(60,60+gridsize*boardsize,130,30); 

复位功能...

public void reset(){ 

game.this.setVisible(false); 
game.this.dispose(); 
new game(); 
updateGamesPlayed(); 
} 

是想更新游戏起的作用......

public void updateGamesPlayed() { 
noGamesPlayed ++; 
gamesPlayed.setText("" + noGamesPlayed + " Games Played"); 

} 

帮助赞赏。

+0

我认为updateGamesPlayed()在游戏类中? – JClassic 2014-12-07 18:18:00

+0

如果是的话(并且没有游戏玩家不是静态的),当你调用'新游戏()'时,你正在重新初始化变量。 – JClassic 2014-12-07 18:19:18

+0

它在游戏类中是的,当游戏重置时有没有增加变量的方法? – AW90 2014-12-07 18:32:24

回答

1

将noOfGamesPlayed变量更改为static。该领域不属于对象,而是属于类本身。然后,将updateGamesPlayed更改为静态方法,这样所有游戏对象都会看到相同的numberOfGamesPlayed计数。这样的:

private static int noGamesPlayed = 0; 

public static void updateGamesPlayed() { 
    noGamesPlayed ++; 
} 

然后,在复位方法,创建后,一个新的游戏更新的游戏次数。

public void reset(){ 
    game.this.setVisible(false); 
    game.this.dispose(); 
    updateGamesPlayed(); 
    new game(); 
} 

你也可以让它“自动”通过在游戏构造递增noGamesPlayed。这样你就不需要拨打updateGamesPlayed

+0

完美 - 像一个治疗工作谢谢你! – AW90 2014-12-07 19:04:33

0

你创建一个全新的游戏对象,一个拥有自己noGamesPlayed变量和JTextField中,并有可能调用此方法不会在新显示的GUI

gamesPlayed.setText("" + noGamesPlayed + " Games Played"); 

而是改变gamesPlayed的JTextField更新已经处理的GUI的JTextField。请注意,您的重置方法看起来是递归的。

一种解决方法是调用新创建的游戏对象的updateGamesPlayed(...)方法(注意该类应重命名为Game),并将正确的数字作为参数传入。我不会创建一个新窗口,而是通过更新关键模型变量(确定程序状态的非GUI变量和类)来完成不同的重置操作。 ),然后使用这些变量重置当前显示。

+0

我认为你的方式更好,当我进行一些改进时,我会考虑按照自己的方式进行操作,目前它正在重置。谢谢。 – AW90 2014-12-07 19:06:01