Java猜数字游戏
这个游戏涉及到game和player两个对象,game会产生介于0-9之间的随机数字,而三个player对象会猜测该数字。
程序逻辑:
1.GameLauncher这个类带有main()方法,是程序的入口点。
2.main()方法中会创建出GuessGame队象,并调用它的startGame()方法。
3.startGame()方法是游戏的起点,它会创建3player对象,然后挑出要猜测的随机数字。
程序源代码:
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 targetNumber=(int)(Math.random()*10);
System.out.println(“I’m thinking of a number between 0 and 9…”);
while(true){
System.out.println(“Number to guess is”+targetNumber);
p1.guess();
p2.guess();
p3.guess();
guessp1=p1.number;
System.out.println(“Player one guessed”+guessp1);
guessp2=p2.number;
System.out.println(“Player two guessed”+guessp2);
guessp3=p3.number;
System.out.println(“Player three guessed”+guessp3);
if(guessp1targetNumber){
p1isRight=true;
}
if(guessp2targetNumber){
p2isRight=true;
}
if(guessp3==targetNumber){
p3isRight=true;
}
if(p1isRight || p2isRight || p3isRight){
System.out.println(“We have a winner”);
System.out.println(“Player one got it right?”+p1isRight);
System.out.println(“Player two got it right?”+p2isRight);
System.out.println(“Player three got it right?”+p3isRight);
System.out.println(“Game is over.”); break;
} else{
System.out.println(“Players will have to try again.”);
}
}
}
}
class Player{
int number=0;
public void guess(){
number=(int) (Math.random()*10);
System.out.println(“I’m guessing”+number);
}
}
class GameLauncher{
public static void main(String[] args){
GuessGame game=new GuessGame(); game.startGame();
}
}
运行结果:
I’m thinking of a number between 0 and 9…
Number to guess is4
I’m guessing5
I’m guessing4
I’m guessing8
Player one guessed5
Player two guessed4
Player three guessed8
We have a winner
Player one got it right?false
Player two got it right?true
Player three got it right?false
Game is over.
提示:
每次运行的结果都是不一样的。