玩家类pk小游戏
?玩家類
package com.hp.mxdx;import java.util.Random;/*** 面向對象* 玩家類* 屬性:名字、類型、生命值、防御值、攻擊力* 方法:自我介紹、PK* */ public class Demo1 {//封裝:把屬性設為私有private,提供公共的get和set方法間接訪問,提高安全性private String name; //姓名private String type; //類型:展示、法師private int life; //生命值private int defense; //防御值private int attack; //攻擊力private double baoji; //暴擊/*** 描述自己的屬性* @return*/public void say(){System.out.println("我叫"+name+",是一個"+type+",生命值高達"+life+",防御值"+defense+",攻擊力"+attack);}/*** 我方開啟的戰斗* @return P 敵對玩家*/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;/*** 測試玩家類* 創建玩家對象PK*/ 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);} }總結
- 上一篇: 即时通讯系统架构设计-如何设计一款Wha
- 下一篇: 2、用Keil新建TM4C123G工程步