标签:
简述:游戏涉及到game和player两个对象,game会产生介于0-9之间的随机数
程序逻辑:
类:
GameLauncher.class
1 public class Gamelauncher { 2 public static void main(String[] args) { 3 GuessGame game = new GuessGame(); 4 game.startGame(); 5 } 6 }
GuessGame.class
1 public class GuessGame{ 2 //用3个实例变量分别表示3个player对象 3 Player p1; 4 Player p2; 5 Player p3; 6 public void startGame(){ 7 //创建player对象 8 p1= new Player(); 9 p2 = new Player(); 10 p3= new Player(); 11 //定义3个变量来保存是否猜中 12 int guessp1 = 0; 13 int guessp2 =0; 14 int guessp3 = 0; 15 //定义3个变量来保存猜测的数字 16 boolean p1isright = false; 17 boolean p2isright =false; 18 boolean p3isright =false; 19 int tarnum =(int)(Math.random()*30); //产生谜底数字 20 System.out.println("i guess 1 to 30"); 21 while(true) 22 { 23 System.out.println("number to guess is "+tarnum); 24 p1.guess(); //调用Player中guess方法 25 p2.guess(); 26 p3.guess(); 27 //取得每个player所猜测的数字将其列出 28 guessp1 =p1.number; 29 System.out.println("one "+guessp1 ); 30 guessp2 = p2.number; 31 System.out.println("two "+guessp2); 32 guessp3=p3.number; 33 System.out.println("three "+guessp3); 34 //检查是否猜中, 35 if (guessp1==tarnum) 36 { 37 p1isright=true; 38 } 39 if (guessp2==tarnum) 40 { 41 p2isright=true; 42 } 43 if (guessp3==tarnum) 44 { 45 p3isright=true; 46 } 47 //如果猜中一个或者多个... 48 if(p1isright||p2isright||p3isright) 49 { 50 System.out.println("we are a winner"); 51 System.out.println("one "+p1isright); 52 System.out.println("two "+p2isright); 53 System.out.println("three "+p3isright); 54 System.out.println("game is over"); 55 break; //因为上面while为true,所以会一直执行,直到if语句为真,执行下面的break才会结束循环 56 } 57 else 58 {System.out.println("123");} 59 } 60 } 61 }
Player.class
1 public class Player { 2 int number = 0; //要被猜的数字 3 public void guess(){ 4 number =(int )(Math.random()*30); 5 System.out.println("i guessing"+number); 6 } 7 }
标签:
原文地址:http://www.cnblogs.com/8013-cmf/p/4758160.html