Java小小RPG遊戲第二版 (基於第一版優化)

英雄打怪物,源碼如下
package com.game.huntervsmonster01;

public class Hunter
{
	String name;
	int life;
	boolean isLive;
	String weapon;
	int attack;
	int defend;

	public Hunter(int i)
	{
		switch (i)
		{
		case 1:
			this.name = "孫悟空";
			break;
		case 2:
			this.name = "景天";
			break;
		case 3:
			this.name = "李逍遙";
			break;
		}
	}

	public Hunter(int i, int life, boolean isLive, String weapon, int attack,
			int defend)
	{
		this(i);
		this.life = life;
		this.isLive = isLive;
		this.weapon = weapon;
		this.attack = attack;
		this.defend = defend;
	}

	void fight(Monster monster)
	{
		if (!isLive)
		{
			return;
		}
		monster.injured(this.attack);
		show();
	}

	void injured(int mattack)
	{
		if (mattack >= this.defend)
			this.life = this.life - (mattack - this.defend);
		if (this.life <= 0)
		{
			dead();
			return;
		}
	}

	void dead()
	{
		this.isLive = false;
	}

	void show()
	{
		if (this.isLive)
			System.out.println(this.name + "還有" + this.life + "點血");
		else
			System.out.println(this.name + "壯烈犧牲了!");
	}
}

package com.game.huntervsmonster01;

public class Monster
{
	String type;
	int life;
	boolean isLive;
	int attack;
	int defend;

	public Monster(int i)
	{
		switch (i)
		{
		case 1:
			this.type = "小殭屍";
			break;
		case 2:
			this.type = "大殭屍";
			break;
		case 3:
			this.type = "殭屍老大";
			break;
		case 4:
			this.type = "小鬼";
			break;
		case 5:
			this.type = "老鬼";
			break;
		case 6:
			this.type = "火鬼王";
			break;
		case 7:
			this.type = "黑無常";
			break;
		case 8:
			this.type = "白無常";
			break;
		case 9:
			this.type = "閻王";
			break;
		}
	}

	public Monster(int i, int life, boolean isLive, int attack, int defend)
	{
		this(i);
		this.life = life;
		this.isLive = isLive;
		this.attack = attack;
		this.defend = defend;
	}

	public void fight(Hunter hunter)
	{
		if (!isLive)
		{
			return;
		}
		hunter.injured(this.attack);
		show();
	}

	public void injured(int hattack)
	{
		if (hattack >= this.defend)
			this.life = this.life - (hattack - this.defend);
		if (this.life <= 0)
		{
			dead();
			return;
		}
	}

	void dead()
	{
		this.isLive = false;
	}

	void show()
	{
		if (this.isLive)
			System.out.println(this.type + "還有" + this.life + "點血");
		else
			System.out.println(this.type + "被殺死了!");
	}
}

package com.game.huntervsmonster01;

public class TestGme
{
	int i;

	public static void main(String[] args)
	{
		Hunter hunter = new Hunter(1, 100, true, "金箍棒", 30, 12);
		Monster monster = new Monster(1, 200, true, 13, 1);
		System.out.println(hunter.name + "VS" + monster.type);
		while (hunter.isLive && monster.isLive)
		{
			hunter.fight(monster);
			/*
			 * if(hunter.isLive || monster.isLive) break;
			 */
			monster.fight(hunter);
			/*
			 * if(hunter.isLive || monster.isLive) break;
			 */
		}
		System.out.println("戰鬥結束");
		monster.show();
		hunter.show();
	}
}


發佈了34 篇原創文章 · 獲贊 3 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章