玩家类
package com.hp.mxdx;
import java.util.Random;
public class Demo1 {
//封装:把属性设为私有private,提供公共的get和set方法间接访问,提高安全性
private String name; //姓名
private String type; //类型:展示、法师
private int life; //生命值
private int defense; //防御值
private int attack; //攻击力
private double baoji; //暴击
public void say(){
System.out.println("我叫"+name+",是一个"+type+",生命值高达"+life+",防御值"+defense+",攻击力"+attack);
}
public void pk(Demo1 demo1) {
//回合制,直到一方死亡停止
int flag = 0;//默认我方先攻击
while (true) {
//显示一下当前战斗人员的信息
this.say();
demo1.say();
Random a = new Random();
//定义一个标记,0我方攻击 1敌方攻击
if (flag == 0) {
int x = a.nextInt(1);
if (x != 2){
int b = a.nextInt(4);
if(b!=0 && b!=1){
this.setAttack(this.attack*b);
System.out.println("龙傲天"+"[暴击!]"+b);
}
}
//战斗 我方攻击力-敌方防御力=伤害值
int harm = this.attack - demo1.defense;
//让敌方生命值-伤害值
demo1.setLife(demo1.life -= harm);
System.out.println(demo1.name + "掉血" + harm);
flag = 1;//改变标记,转换攻击角色
} else {
//战斗 敌方攻击力-我方防御力=伤害值
int x = a.nextInt(1);
if (x != 2){
int b = a.nextInt(4);
if(b!=0 && b!=1){
demo1.setAttack(demo1.attack*b);
System.out.println("赵日天"+"[暴击!]"+b);
}
}
int harm = demo1.attack - this.defense;
this.setLife(this.life -= harm);
System.out.println(this.name + "掉血" + harm);//让我方生命值-伤害值
flag = 0; //改变标记,转换攻击角色
}
//有血量<=0,战斗结束
if (this.life <= 0){
System.out.println(demo1.name+"打败了"+this.name);
int x = a.nextInt(3);
if (x == 2){
System.out.println("赵日天获取SSS级大杖");
}else {
System.out.println("获取1000金币");
}
break;//结束循环
}
if (demo1.life <= 0){
System.out.println(this.name+"打败了"+demo1.name);
int x = a.nextInt(3);
if (x == 2){
System.out.println("龙傲天获取SSS级大剑");
}else {
System.out.println("获取1000金币");
}
break;//结束循环
}
//线程休眠
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//构造器(建议如果定义了有参的构造器,一定定义一个无参构造器)
public Demo1(String name, String type, int life, int defense, int attack) {
this.name = name;
this.type = type;
this.life = life;
this.defense = defense;
this.attack = attack;
}
public Demo1(double baoji) {
this.baoji = baoji;
}
//无参构造器
public Demo1() {
}
//get和set方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getLife() {
return life;
}
public void setLife(int life) {
this.life = life;
}
public int getDefense() {
return defense;
}
public void setDefense(int defense) {
this.defense = defense;
}
public int getAttack() {
return attack;
}
public void setAttack(int attack) {
this.attack = attack;
}
public double getBaoji() {
return baoji;
}
public void setBaoji(double baoji) {
this.baoji = baoji;
}
}
实现类
package com.hp.mxdx;
public class Test {
public static void main(String[] args) {
//创建两个玩家
Demo1 demo1 = new Demo1("龙傲天", "战士", 1000, 55, 80 );
Demo1 demo2 = new Demo1("赵日天", "法师", 1000, 48, 95);
//战斗
demo1.pk(demo2);
}
}



