1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > 简单的奥特曼打小怪兽

简单的奥特曼打小怪兽

时间:2022-08-14 19:54:39

相关推荐

简单的奥特曼打小怪兽

奥特曼打小怪兽

需求

创建两个类,一个奥特曼类,一个怪兽类, 分别有各自对应的属性和方法

编写一个测试类,实现奥特曼与怪兽的创建,并让他们两个互相攻击,最后给出胜利结果

说明

奥特曼

属性:

血量

攻击力

行为:

攻击小怪兽

详细代码

奥特曼类

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("奥特曼赢了");}}}

总结

在奥特曼与小怪兽相互攻击时,需要传入对应的对象,如在奥特曼攻击怪兽的时候,传入了要攻击的怪兽对象

在奥特曼攻击怪兽时,调用了怪兽自己的减血方法,这样不会破坏封装对象的原则,只能自己修改自己的属性。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。