模拟射击文字类游戏

题目:一个简单的对象设计实验:开枪射击。

  思路:对象有人、枪、弹夹,

  人是用枪发射弹夹中;子弹在弹夹中,弹夹在枪中,枪在人手中。

  因为题目中的人、枪、弹夹并没有给予诸如“子弹的型号、大小等或者枪的类型又或者是弹夹的形状等”详细的说明,所以这里的人、枪、弹夹都是抽象的,忽略掉了子弹和弹夹和枪,它们之间存在的兼容性问题,也就是从广义上讲的“弹夹装子弹,手枪发射弹夹中的子弹”。

  那么,在建立的工程中创造四个类,分别是:Main、People、Gun、Bullet_Box

  Main主要用于执行程序(不多说)

  People(人类)

  Gun(枪类)

  Bullet_Box(弹夹类)

  这里并不需要单独给子弹抽象出一个类,以为子弹仅仅需要被发射就可以了,暂时不需要考虑子弹的伤害等特性,所以可以把子弹作为弹夹类中的成员变量存在着,并且在弹夹类中定义一个方法来查看子弹数量(这也比较符合实际情况)

 

源码:

 1 public class Bullet_Box { // 弹夹类
 2     private int bullet_count; // 子弹数量
 3 
 4     public Bullet_Box() { // 构造方法
 5         this.bullet_count = 0; // 初始化子弹数量
 6     }
 7 
 8     public void Add_bullet(int bullet_count) { // 添加子弹方法
 9         this.bullet_count = bullet_count;
10     }
11 
12     public int See_bullet() { // 查看子弹方法
13         return this.bullet_count;
14     }
15 }

 

 1 public class Gun { // 枪类
 2     private Bullet_Box bullet_Box;
 3 
 4     public Gun(Bullet_Box bullet_box) { // 构造方法
 5         this.bullet_Box = bullet_box;
 6     }
 7 
 8     public void Shoot() { // 射击方法
 9         if (this.bullet_Box.See_bullet() > 0) {
10             this.bullet_Box.Add_bullet(this.bullet_Box.See_bullet() - 1);
11             System.out.println("砰——   " + "当前子弹数量: " + this.bullet_Box.See_bullet() + " 发");
12         } else {
13             System.out.println("子弹数量不足!");
14         }
15     }
16 }

 

 1 public class People { // 人类
 2     private Gun gun;
 3 
 4     public People(Gun gun) { // 构造方法
 5         this.gun = gun;
 6     }
 7 
 8     public void StartFire() { // 开枪
 9         this.gun.Shoot();
10     }
11 
12 }

 

 1 public class Main {
 2     public static void main(String[] args) throws InterruptedException {
 3         Bullet_Box bullet_Box = new Bullet_Box();
 4         bullet_Box.Add_bullet(5);
 5         Gun gun = new Gun(bullet_Box);
 6         People people = new People(gun);
 7 
 8         while (true) {
 9             people.StartFire();
10             Thread.sleep(1000);
11         }
12     }
13 }

 

运行结果:

 

 

动态效果:

posted @ 2020-02-23 16:14  锤子猫  阅读(291)  评论(0编辑  收藏  举报