一個文字版Java雙人對抗遊戲源碼

Main.java 

import javax.swing.JLabel;
import javax.swing.JOptionPane;

public class Main {
	public static void main(String[] args) {
		Warrior p1 = new Warrior(
			JOptionPane.showInputDialog(null, p("請輸入第一位玩家的暱稱"), "第一位玩家", JOptionPane.QUESTION_MESSAGE)
		);
		Warrior p2 = new Warrior(
				JOptionPane.showInputDialog(null, p("請輸入第二位玩家的暱稱"), "第二位玩家", JOptionPane.QUESTION_MESSAGE)
		);
		p1.hit(p2);
	}
	
	private static JLabel p(String text){
		//使用HTML包裝字符串,以改變原字體
		return new JLabel("<html><h2>" + text + "</h2></html>");
	}
}

Warrior.java

import javax.swing.*;

public class Warrior {
	private String name;
	private int blood = 200;
	private static int sum = 0;
	
	public void hit(Warrior enemy){
		sum ++;
		String referee = "";
		int attack;
		int trick = random(0, 7);
		switch (trick) {
		case 0:
			attack = random(2, 10);
			referee = this + "炫耀了他的大塊肌肉," + enemy + "損失了" + attack + "點血量";
			break;
		case 1:
			attack = random(10, 15);
			referee = this + "使用了魅惑技能," + enemy + "被迷的神魂顛倒,瞬間掉了2W的粉絲,損失了" + attack + "點血量";
			break;
		case 2:
			attack = random(10, 20);
			referee = this + "查看了葵花寶典,逼格提升了" + attack + "%," + enemy + "被嚇破了膽,損失了" + attack + "點血量";
			break;
		case 3:
			attack = random(6, 10);
			referee = this + "發起了猛烈的進攻,打的" + enemy + "滿地找牙,讓他損失了" + attack + "點血量";
			break;
		case 4:
			attack = random(10, 25);
			referee = this + "狠狠的鄙視了" + enemy + "一下,給" + enemy + "留下了心理陰影,使他損失了" + attack + "點血量";
			break;
		case 5:
			attack = random(10, 50);
			referee = this + "使用了必殺技," + enemy + "的假髮被打掉了!讓他損失了" + attack + "點血量";
			break;
		case 6:
			attack = random(1, 5);
			referee = this + "絆了一腳,只對" + enemy + "造成了" + attack + "點傷害";
			break;
		default:
			attack = random(13, 23);
			referee = this + "使用了情侶花式虐狗秀恩愛,一下子擊中了" + enemy + "的小心臟,打掉了他" + attack + "點血量";
			break;
		}
		enemy.setBlood(getBlood() - attack);
		JOptionPane.showMessageDialog(null, p(referee, enemy), "第" + sum + "回合", JOptionPane.INFORMATION_MESSAGE);
		if(enemy.blood <= 0){
			JOptionPane.showMessageDialog(null, enemy + "精疲力盡,掛掉了!", "K.O.", JOptionPane.ERROR_MESSAGE);
			System.out.println();
			return;
		}
		enemy.hit(this);
	}
	
	private JLabel p(String text, Warrior enemy){
		//使用HTML包裝字符串,以改變原字體
		return new JLabel("<html><h2 style=\"color:#c23616; font-family:'微軟雅黑';\">" + text + "</h2><h3 style=\"text-align:center;color:#8c7ae6;\">"
		+ this + ":" +this.getBlood() + " & " + enemy + ":" +enemy.getBlood() + "</h3></html>");
	}
	
	public int random(int min,int max){
		return (int)(Math.random() * (max - min + 1)) + min;
	}
	
	@Override
	public String toString() {
		return "【" + this.name + "】";
	}
	
	public Warrior(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}
	
	public int getBlood() {
		return blood;
	}
	
	public void setBlood(int blood) {
		this.blood = blood;
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章