凹凸曼
package com.flagwu;
/**
* 凹凸曼
* @author XiaoWu
*
*/
public class Ultraman {
private static final int MAX_MAGIC = 100;
private String name; //名字
private int hp; //生命值
private int mp; //魔法值
/**
* 构造器
* @param name
*/
public Ultraman(String name){
this.name = name;
this.hp = 300;
this.mp = MAX_MAGIC;
}
/**
* 普通攻击
* @param m
*/
public void attack(Monster m){
int injury = (int) (Math.random() * 18 + 10);
m.setHp(m.getHp() - injury);
}
public int getMp() {
return mp;
}
public void setMp(int mp) {
this.mp = mp < MAX_MAGIC? mp : MAX_MAGIC;
}
/**
* 必杀技
* @param m
*/
public void hugeAttack(Monster m){
m.setHp(m.getHp() - 80);
}
/**
* 魔法攻击
* @param ms 小怪兽的数组
*/
public void magicAttack(Monster[] ms){
mp -= 30;
for(int i = 0;i < ms.length; i++){
Monster m = ms[i];
if(m.isAlive()){
m.setHp(getHp() - 30);
}
}
}
public int getHp() {
return hp;
}
public void setHp(int hp) {
this.hp = hp > 0? hp : 0;
}
@Override
public String toString() {
return "凹凸曼" + name + "生命值:" + hp;
}
}
小怪兽
package com.flagwu;
/**
* 小怪兽
* @author XiaoWu
*
*/
public class Monster {
private String name;
private int hp;
/**
* 构造器
* @param name
*/
public Monster(String name){
this.name = name;
this.hp = 1000;
}
/**
* 攻击
* @param 凹凸曼
*/
public void attack(Ultraman u){
int injury = (int) (Math.random() * 9 + 3);
u.setHp(u.getHp() - injury);
}
public int getHp() {
return hp;
}
public void setHp(int hp) {
this.hp = hp > 0? hp : 0;
}
@Override
public String toString() {
return "小怪兽" + name + "生命值:" + hp;
}
/**
* 判断死活
* @return 活着返回true死了返回false
*/
public boolean isAlive() {
return hp > 0;
}
public String getName() {
return name;
}
}
凹凸曼打小怪兽
package com.flagwu;
/**
* 凹凸曼打小怪兽
* @author XiaoWu
*
*/
public class PK {
/**
* 判断是否至少有一只小怪兽是活着的
* @param ms 小怪兽的数组
* @return 有活着的小怪兽返回true否则返回false
*/
public static boolean hasAliveMonster(Monster[] ms){
for(int i = 0; i < ms.length; i++){
if(ms[i].isAlive()){
return true;
}
}
return false;
}
public static void main(String[] args) {
Ultraman u = new Ultraman("taro");
Monster[] ms = {new Monster("titan"),new Monster("A"),new Monster("B")};
int round = 1;
do{
System.out.println("===第" + round++ + "回合===");
Monster m = null;
do{
int mIndex = (int) (Math.random() * ms.length);
m = ms[mIndex];
}while(!m.isAlive());
System.out.println(m.getName() + "小怪兽攻击凹凸曼");
m.attack(u);
System.out.println(u);
if(u.getHp() > 0){
double rate = Math.random();
if(rate <= 0.8){
System.out.println("凹凸曼对小怪兽使用普通攻击");
u.attack(m);
}
else if(rate <= 0.9){
System.out.printf("凹凸曼使用单体技能\n效果显著!\n");
u.hugeAttack(m);
}
else{
if(u.getMp() >= 30){
System.out.println("凹凸曼对小怪兽使用魔法攻击!");
u.magicAttack(ms);
}
else{
System.out.println("凹凸曼魔法不足!");
}
}
}
for(Monster tempMonster : ms)
System.out.println(tempMonster);
}while(u.getHp() > 0 && hasAliveMonster(ms));
if(u.getHp() > 0){
System.out.println("凹凸曼胜利!");
}
else{
System.out.println("小怪兽胜利!");
}
}
}