
附:TestingMonster代码段
import java.util.*;
/**
* Title : TestingMonsters.java
* Description: This class is the test class for Monsters.
* @author Laurissa Tokarchuk
* @version 1.0
* @author Paula Fonseca
* @version 1.1
*/
public class TestingMonsters {
public static void main(String[] args) {
ArrayList<Monster> monsters = new ArrayList<Monster>();
monsters.add(new Monster("Tom"));
monsters.add(new Monster("George"));
monsters.add(new Dragon("Smaug"));
monsters.add(new Dragon("Jabosh"));
monsters.add(new Troll("Salomon"));
monsters.add(new Troll("Bender"));
int damageDone = 0;
while (damageDone < 100) {
for (Monster m : monsters) {
m.move((int)(Math.random()*4) + 1);
damageDone += m.attack();
}
}
}
}
java程序
代码1:Monster.java
//import java.lang.runtime.SwitchBootstraps;
public class Monster {
public String name;
public Monster(String name) {
this.name = name;
}
public int attack() {
int x = (int) (Math.random() * 5 + 1);
System.out.println(this.name + ", of type "
+ getClass() + ", attacks generically: "
+ x + " points damage caused. ");
return x;
}
public void move(int direction) {
switch(direction) {
case 1: {
System.out.println(this.name +" is moving 1 step North. ");
break;
}
case 2:{
System.out.println(this.name +" is moving 1 step East. ");
break;
}
case 3:{
System.out.println(this.name +" is moving 1 step South. ");
break;
}
default:
System.out.println(this.name +" is moving 1 step West. ");
break;
}
}
}
代码2:Dragon.java
public class Dragon extends Monster{
public Dragon(String name){
super(name);
this.name = name;
}
@Override
public int attack() {
int probability = (int)(Math.random()*10 + 1);
int x;
if(probability <= 3) {
x = (int) (Math.random()*50 + 1);
System.out.println(this.name + ", of type "+ getClass()
+ ", attacks bby breathing fire: " + x
+ " points damage caused. ");
}
else {
x = super.attack();
}
return x;
}
}
代码3:Troll.java
public class Troll extends Monster{
public Troll(String name){
super(name);
if(name.equals("Saul") || name.equals("Salomon")){
System.out.println("This name is not available." );
this.name = "Detritus";
}
}
public String name(){
return this.name;
}
}
代码4:TestingMonster.java
import java.util.*;
public class TestingMonster {
public static void main(String[] args){
ArrayList<Monster> monsters = new ArrayList<Monster>();
monsters.add(new Monster("Tom"));
monsters.add(new Monster("George"));
monsters.add(new Dragon("Smaug"));
monsters.add(new Dragon("Jabosh"));
monsters.add(new Troll("Salomon"));
monsters.add(new Troll("Bender"));
int damageDone = 0;
while (damageDone < 100) {
for (Monster m : monsters) {
m.move((int)(Math.random()*4) + 1);
damageDone += m.attack();
}
}
}
}
这个博客展示了如何使用Java编程创建一个怪物战斗模拟器。`TestingMonster`类管理一组怪物,包括`Monster`、`Dragon`和`Troll`子类。每个怪物有不同的攻击和移动行为。`Dragon`有概率喷火造成高伤害,而`Troll`在初始化时会检查名字。程序通过循环战斗直到总伤害达到100。

被折叠的 条评论
为什么被折叠?



