package problem1;
public class Monster
{
String name;
public Monster(String name)
{
this.name = name;
}
public int attack()
{
int x;
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;
}
}
}
备注:生成随机数1-x: math.random()*x+1
package problem1;
public class Dragon extends Monster
{
public Dragon(String name)
{
super(name);
this.name = name;
}
// override the attack
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 by breathing fire: " + x
+ " points damage caused.");
} else
{
x = super.attack();
}
return x;
}
}
Note:
难点1:30% of the time
解决思路: 生成一个1-10 的随机数 然后 若1-3 则使用breathing the fire 来攻击
难点2: 如何一起使用 breathing the fire 与 常规攻击?
x = super.attack();
package problem1;
public class Troll extends Monster
{
public Troll(String name)
{
super(name);
// this.name = name;
if (name.equals("Saul") || name == "Salomon")
{
System.out.println("wrong name");
this.name = "Detritus";
}
}
public String getName()
{
return this.name;
}
}
Note:
1、对于super的理解:使用父类的此方法,里面的东西就不用再写了,super括号里面就是给父类对应方法传的参数
2、对于equals的理解: equals() 是一个class中的一种方法,可以比较此 . 前面对应的值 和括号里面的值是否相等
public boolean equals(Object obj) {
return (this == obj);
}
如比较两个字符串是否相等:
String s1 = “fang”;
boolean test = s1.equals(“fang”)// true
(别忘了要有一个 boolean值 承接equals 返回的值)
package problem1;
import java.util.ArrayList;
public class TestingMonster
{
public static void main(String[] args)
{
ArrayList<Monster> monsters = new ArrayList<>();
monsters.add(new Monster("Tom"));
monsters.add(new Monster("Geooge"));
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 = damageDone + m.attack();
}
}
}
}