学习了这么久,我们来玩个小游戏吧!( 模拟 游戏的运行)
在多个类中创建的, 方便大家看代码,我把代码全部放到一个里面
package com.maya.youxi; public class ZuoZhan { //建立父类 protected String Name; protected int GongJiLi; protected int HP; public ZuoZhan(String a,int b,int c){ this.Name =a; this.GongJiLi =b; this.HP =c; } public void GongJi(){ } public void ShouShang(){ } public void TaoPao(){ } public void DiTaoPao(){ } } public class ShiBing extends ZuoZhan { //士兵类 public ShiBing(String a, int b, int c) { super(a,b,c); } public void GongJi(){ int x=(int)(Math.random()*1000); System.out.println("我方"+this.Name+"攻击敌方坦克,攻击力为"+this.GongJiLi+",敌方坦克剩余血量"+x); if(x<200) { this.DiTaoPao(); } } public void ShouShang(){ int y=(int)(Math.random()*100); if(y<this.GongJiLi+40) { x+=40; } System.out.println("我方"+this.Name+"受到敌方坦克攻击,坦克攻击力为"+(this.GongJiLi+40)+"士兵受到"+x+"点伤害,剩余血量"+(this.HP-x)); if((this.HP-x)<=20){ this.TaoPao(); } } public void TaoPao(){ System.out.println("我方"+this.Name+"逃跑了"); } public void DiTaoPao(){ System.out.println("敌方坦克逃跑了"); } } public class Tank extends ZuoZhan { //坦克类 public Tank(String a, int b, int c) { super(a,b,c); } public void GongJi(){ int x=(int)(Math.random()*1000); System.out.println("我方"+this.Name+"攻击敌方坦克,攻击力为"+this.GongJiLi+",敌方坦克剩余血量为"+x); if(x<300) { this.DiTaoPao(); } } public void ShouShang(){ int x=((int)(Math.random()*1000)); if(x<this.GongJiLi) { x=x+100; } System.out.println("我方"+this.Name+"受到敌方坦克攻击,坦克攻击力为"+this.GongJiLi+",我方坦克受到"+x+"点伤害,剩余血量"+(this.HP-x)); if(this.HP-x<200){ this.TaoPao(); } } public void TaoPao(){ System.out.println("我方坦克逃跑了"); } public void DiTaoPao(){ System.out.println("敌方坦克逃跑了"); } } public class CaoZong { //统一参数 public void Dong(ZuoZhan z){ z.GongJi(); z.ShouShang(); } } public class text { //测试 public static void main (String[] args){ CaoZong z=new CaoZong(); ShiBing s=new ShiBing("士兵",10,100); Tank t=new Tank("坦克", 100, 1000); //z.Dong(s); z.Dong(t); } }
最后模拟的结果为
因为数字为随机数,比如当x和this.HP-x的值少于某个值时,就会触发逃跑方法,高于某个值时,不会触发逃跑方法