【从零学java】猜数字游戏——了解类与对象
作者:互联网
通过猜数字游戏,开始了解类和对象。
游戏概要:产生一个0-9间的随机数,3个player猜,若有猜中者则游戏结束,猜不中下一轮继续猜。
类:GuessGame.class、Player.class、GameLauncher.class
逻辑:
1)GameLauncher作为程序的入口,含有main()方法。
2)main()中创建GuessGame对象,并调用它的startGame()方法。
3)startGame()方法是游戏的起点,创建3个player,然后猜数,并体现猜数的过程。
3个源文件的代码如下:
GuessGame.java
public class GuessGame{ Player p1; Player p2; Player p3; public void startGame(){ p1 = new Player(); p2 = new Player(); p3 = new Player(); int guessp1 = 0; int guessp2 = 0; int guessp3 = 0; boolean p1isRight = false; boolean p2isRight = false; boolean p3isRight = false; int resultNum = (int)(Math.random()*10); System.out.println("I'm thinking of a number between 0 and 9..."); System.out.println("number to guess is "+resultNum); while(true){ p1.guess(); p2.guess(); p3.guess(); guessp1 = p1.number; guessp2 = p2.number; guessp3 = p3.number; if(guessp1 == resultNum){ p1isRight = true; } if(guessp2 == resultNum){ p2isRight = true; } if(guessp3 == resultNum){ p3isRight = true; } System.out.println("player one guessed " + guessp1); System.out.println("player two guessed " + guessp2); System.out.println("player three guessed " + guessp3); if(p1isRight || p2isRight|| p3isRight){ System.out.println("we have a winner!"); System.out.println("one is winner? "+ p1isRight); System.out.println("two is winner? "+ p2isRight); System.out.println("three is winner? "+ p3isRight); System.out.println("Game is over."); break; }else{ System.out.println("try again."); } } } }
Player.java
public class Player{ int number = 0; public void guess(){ number = (int) (Math.random()*10); System.out.println("I guess "+number); } }
GameLauncher.java
public class GameLauncher{ public static void main(String[] args){ GuessGame game = new GuessGame(); game.startGame(); } }
三个文件在同一个目录下,编译时,直接编译带main()方法的源文件,所有相关的源文件都会被编译。
执行如下(每次执行都会不一样,有时会猜好多轮):
要理解的点:
1、如果需要全局变量或者方法时,怎么办?
在java的面向对象概念中,并没有全局变量这回事,有时我们需要
标签:java,游戏,零学,int,System,number,Player,println,out 来源: https://www.cnblogs.com/brigth-9V/p/10360308.html