publicclassGameStartStateimplementsGameState {/*击杀一只怪物*/ @OverridepublicvoidkillMonster() {System.out.println("Kill a Monster"); }/*获得5经验值*/ @OverridepublicvoidgainExperience() {System.out.println("Gain 5 EXP"); }/*进入下一关*/ @Overridepublicvoidnext() {System.out.println("Good! please enter next level"); }/*捡到一件好东西*/ @Overridepublicvoidpick() {System.out.println("Wow! You pick a good thing"); }}
游戏结束状态
publicclassGameOverStateimplementsGameState {/*游戏没开始,无法打怪*/ @OverridepublicvoidkillMonster() {System.out.println("Please start game first"); }/*游戏没开始,无法获得经验*/ @OverridepublicvoidgainExperience() { }/*游戏已经结束,下一步就是选择是否重新开始*/ @Overridepublicvoidnext() {System.out.println("You want to challenge again?"); }/*游戏没开始,无好东西可以捡*/ @Overridepublicvoidpick() {System.out.println("Please start game first"); }}
什么状态下该干什么都已经想好了,下一步就是来一个玩家开始游戏了
publicclassPlayer {/*游戏状态*/GameState state;/*游戏状态的设置*/publicvoidsetState(GameState state) {this.state= state; }/*游戏开始*/publicvoidgameStart() {setState(new GameStartState());System.out.println("\n-----Game Start, ready to fight-----\n"); }/*游戏结束*/publicvoidgameOver(){setState(new GameOverState());System.out.println("\n----- Game Over -----\n"); }/*打怪*/publicvoidkillMonster(){state.killMonster(); }/*获得经验*/publicvoidgainExperience() {state.gainExperience(); }/*下一关*/publicvoidnext(){state.next(); }/*捡东西*/publicvoidpick(){state.pick(); }publicstaticvoidmain(String[] args) {/*游戏开始后的一系列操作和结束后的操作*/Player player =newPlayer();player.gameStart();player.killMonster();player.gainExperience();player.next();player.pick();player.gameOver();player.next();player.killMonster();player.pick(); }}
-----Game Start, ready to fight-----
Kill a Monster
Gain 5 EXP
Good! please enter next level
Wow! You pick a good thing
----- Game Over -----
You want to challenge again?
Please start game first
Please start game first