今天看了前三章,作为一个初学者,感觉这本书还是很让我感兴趣的,它里面的一些插画和游戏,能让你学起来没那么枯燥。
自己尝试着把里面一个较为简单的游戏写了一遍。
游戏设计到game和player两个对象。game会产生介于0~9之间的随机数字,3个player对象会猜测该数字,1个player猜到就结束游戏。
package study;
public class Count {
//用三个实例对象表示三个player对象
Player p1;
Player p2;
Player p3;
public void StartGame() {
//创建出player对象
p1 = new Player();
p2 = new Player();
p3 = new Player();
//给他们猜测的值赋为0
int guessp1 = 0;
int guessp2 = 0;
int guessp3 = 0;
//用来判断是否猜测正确
boolean P1guess = false;
boolean P2guess = false;
boolean P3guess = false;
//随机生成0~9的整数
int random1 = (int) (Math.random()*10);
while(true) {
System.out.println("number is "+random1);
//调用guess方法
p1.guess();
p2.guess();
p3.guess();
//guess方法中的值赋给player对象
guessp1 = p1.number;
System.out.println("p1 guess number is "+guessp1);
guessp2 = p2.number;
System.out.println("p2 guess number is "+guessp2);
guessp3 = p3.number;
System.out.println("p3 guess number is "+guessp3);
//判断猜测的数值与随机数值是否相同
if(guessp1 == random1) {
P1guess = true;
}
if(guessp2 == random1) {
P2guess = true;
}
if(guessp3 == random1) {
P3guess = true;
}
//如果有一个或多个猜中,就打印结果并结束
if(P1guess || P2guess || P3guess) {
System.out.println("player win the game");
System.out.println("p1 win the game? "+P1guess);
System.out.println("p2 win the game? "+P2guess);
System.out.println("p3 win the game? "+P3guess);
System.out.println("game over");
break;
}else {//否则继续游戏
System.out.println("you lose");
}
}
}
//主方法,开始游戏
public static void main(String[] args) {
Count game = new Count();
game.StartGame();
}
}
//创建player类
class Player {
int number = 0;
//随机生成player猜测的数
public void guess() {
number = (int) (Math.random()*10);
System.out.println("i guess number is "+ number);
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)