package com.lovo;
/**
* 奥特曼
* @author Even
*
*/
public class Ultraman {
private String name;
private int hp;
private int mp;
/**
* 构造器
* @param name
*/
public Ultraman(String name) {
this.name = name;
this.hp = 300;
this.mp = 100;
}
public int getHp() {
return hp;
}
public void setHp(int hp) {
this.hp = hp > 0? hp: 0;
}
public int getMp() {
return mp;
}
public void setMp(int mp) {
this.mp = mp;
}
/**
* 攻击
* @param m
*/
public void attack(Monster m){
int injury = (int)(Math.random()*21+10);
m.setHp(m.getHp()- injury);
}
/**
* 究极必杀技
* @param m
*/
public void hugeAttack(Monster m){
m.setHp(m.getHp()-50);
}
/**
* 魔法攻击
* @param m
*/
public void magicAttack(Monster[] ms){
for(int i = 0; i < ms.length;i++){
Monster m = ms[i];
if(m.isAlive()){
m.setHp(m.getHp()-20);
}else{
m.setHp(0);
}
}
}
@Override
public String toString() {
return "Ultraman 的生命值为" + hp;
}
}
package com.lovo;
/**
* 小怪兽
*/
public class Monster {
private String name;
private int hp;
public int getHp() {
return hp;
}
public void setHp(int hp) {
this.hp = hp > 0 ? hp : 0;
}
public Monster(String name) {
this.name = name;
this.hp = 100;
}
public void attack(Ultraman u){
int injury = (int)(Math.random()*11+5);
u.setHp(u.getHp()-injury);
}
@Override
public String toString() {
return "Monster 的生命值为" + hp;
}
public boolean isAlive(){
return this.hp>0;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.lovo;
public class PK {
public static boolean hasAliveMonster(Monster[] ms){
boolean alive = false;
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("肖继潮");
Monster[] ms = {
new Monster("张三"),
new Monster("李四"),
new Monster("刘五"),
new Monster("王六"),
new Monster("张七"),
};
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(u);
System.out.println(m);
m.attack(u);
System.out.println(m.getName()+"小怪兽攻击奥特曼");
if(u.getHp()>0){
u.setMp(u.getMp()+5);
double rate = Math.random();
if(rate <= 0.8){
System.out.println("奥特曼攻击小怪兽");
u.attack(m);
}
else if(rate <= 0.9){
System.out.println("奥特曼使用究极必杀技");
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("小怪兽胜利");
}
}
}