简单的奥特曼打小怪兽

奥特曼打小怪兽

需求

创建两个类,一个奥特曼类,一个怪兽类, 分别有各自对应的属性和方法
编写一个测试类,实现奥特曼与怪兽的创建,并让他们两个互相攻击,最后给出胜利结果

说明

奥特曼
属性:
血量
攻击力
行为:
攻击小怪兽

详细代码

奥特曼类

public class Altman {

	// 定义属性
	private int HP;
	private int damage;
	
	public int getHP() {
		return HP;
	}

	public void setHP(int hP) {
		HP = hP;
	}

	public int getDamage() {
		return damage;
	}

	public void setDamage(int damage) {
		this.damage = damage;
	}

	// 定义攻击方法,传入对象为小怪兽
	public void attack(Monster monster) {
		// 调用怪兽自己的减血方法,完成攻击
		monster.underAttack(this.damage);
	}
	
	// 奥特曼自己的减血方法
	public void underAttack(int damage) {
		this.HP -= damage;
		if (this.HP < 0) {
			this.HP = 0;
		}
	}
	
	// 判断死亡状态
	public boolean isDead() {
		return this.HP != 0 ? false : true;
	}
}

怪兽类

public class Monster {

	// 定义属性
	private int HP;
	private int damage;
	
	public int getHP() {
		return HP;
	}
	
	public void setHP(int hP) {
		HP = hP;
	}
	
	public int getDamage() {
		return damage;
	}
	
	public void setDamage(int damage) {
		this.damage = damage;
	}
	
	// 定义攻击方法,传入对象为奥特曼
	public void attack(Altman altman) {
		// 调用怪兽自己的减血方法,完成攻击
		altman.underAttack(this.damage);
	}
	
	// 怪兽自己的减血方法
	public void underAttack(int damage) {
		this.HP -= damage;
		if (this.HP < 0) {
			this.HP = 0;
		}
	}
	
	// 判断死亡状态
	public boolean isDead() {
		return this.HP != 0 ? false : true;
	}
}

Main方法测试

public class Main {
	public static void main(String[] args) throws InterruptedException {
	
		// 初始化奥特曼与怪兽
		Altman atm = new Altman();
		Monster gsl = new Monster();
		
		// 设定初始生命值
		atm.setHP(100);
		gsl.setHP(1000);
		
		// 定义回合数
		int count = 0;
		
		// 循环攻击,直到有一方死亡,停止循环
		while (!atm.isDead() && !gsl.isDead()) {
		
			// 获取随机攻击值
			atm.setDamage((int)(Math.random() * 100) + 1);
			gsl.setDamage((int)(Math.random() * 10) + 1);
			
			System.out.println("*************第" + (++count) + "回合**************");
			// 随机攻击
			if (((int)(Math.random() * 2) + 1) % 2 == 0) {
				atm.attack(gsl);
				System.out.println("奥特曼正在攻击怪兽...");
			} else {
				gsl.attack(atm);
				System.out.println("怪兽正在攻击奥特曼...");
			}
			
			// 程序休眠,使程序运行看起来有回合感
			// 可以注释掉
			Thread.sleep(2000);

			// 输出当前血量
			System.out.println("奥特曼剩余血量:" + atm.getHP());
			System.out.println("小怪兽剩余血量:" + gsl.getHP());
		}
		
		// 胜利情况判断
		if (atm.isDead()) {
			System.out.println("怪兽赢了");
		} else {
			System.out.println("奥特曼赢了");
		}
	}
}

总结

在奥特曼与小怪兽相互攻击时,需要传入对应的对象,如在奥特曼攻击怪兽的时候,传入了要攻击的怪兽对象
在奥特曼攻击怪兽时,调用了怪兽自己的减血方法,这样不会破坏封装对象的原则,只能自己修改自己的属性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值