1. 程式人生 > >java學習2打架代碼編寫

java學習2打架代碼編寫

print 控制臺 取值 eth ext 學習 port void pack

在同一個包中的Player類

package work;

public class Player {
private String name;
private int hp;
private int attack;
public Player(String name,int hp,int attack){//構造函數,初始化值
this.name=name;
this.hp=hp;
this.attack=attack;
}
public void setName(String name) {//獲取值

this.name=name;
}
public String getName(){
return name;
}
public void setHp(int hp){
this.hp=hp;
}
public int getHp(){
return hp;
}
public void setAttack(int attack){
this.attack=attack;
}
public int getAttack(){
return attack;
}/**
*
*攻擊行為、
*player 為攻擊對象
***/
public void hit(Player player){
//被打的對象(血量=血量-本人攻擊力)
player.hp=player.hp-this.attack;
if(player.hp<0){
player.hp=0;
System.out.println(this.name+"攻擊了"+player.name+"打出了"+attack+"點傷害."+player.name+"還剩下多沙"+player.hp+"血量");
}
}
}

在同一個包中另一個Game類

package work;

import java.util.Scanner;
/**
* @author 遊戲
*
*/
public class Game {
Scanner sc=new Scanner(System.in);

// 從控制臺接受數據並且封裝成一個玩家對象

public Player enter(String player) {//封裝玩家信息
System.out.println("輸入"+player+"姓名");
String name=sc.next();
System.out.println("輸入"+player+"血量");
int hp=sc.nextInt();
System.out.println("輸入"+player+"攻擊力");
int attack=sc.nextInt();
Player backPlayer=new Player(name, hp,attack);
return backPlayer;
}
public void start() {
//從封裝好的函數中輸入玩家的信息
Player player1=this.enter("玩家一");
Player player2=this.enter("玩家二");
boolean go=true;
while(go){
//玩家一打了玩家二
player1.hit(player2);
if(player2.getHp()<0){

System.out.println(player1.getName()+"ko了"+player2.getName()+"遊戲結束!fighting!!!!!!!!!!");
break;
}
//玩家二打了玩家一
player2.hit(player1);
if(player1.getHp()<0){

System.out.println(player2.getName()+"ko了"+player1.getName()+"遊戲結束!fighting!!!!!!!!!!");
go=false;
}
}
}
public static void main(String[] args) {
Game game=new Game();
game.start();
}
}

java學習2打架代碼編寫