【小型JavaFx項目】Java的知識點綜合運用之牧場物語遊戲

前言

這已經是幫數媒的同學寫的第三份作業了。。。

第一份:文字小冒險遊戲

第二份:英漢字典

知識點

老樣子,爲了幫他們應付作業隨便寫了點知識點。

  1. 利用JavaFx來製作界面,實現了一個牧場遊戲的界面,界面優美精良,用到了BorderPane佈局。
  2. JavaFx的UI組件利用了Button,Label,Image,ImageView,ListView等。
  3. JavaFx通過ActionEvent添加了事件,【購買寵物】,【出售寵物】,【餵食寵物】,【寵物喝水】,【寵物喝水】,【陪玩寵物】,【遊戲開始】。
  4. JavaFx利用Alert類實現了彈框,包括提示類彈框與輸入類彈框,利用Result類接收了輸入類彈框的結果。
  5. 使用了面向對象的方式編程:
    (1)構造了AnimalInterface接口,定義了動物類的規範,擁有eat(),drink(),wantPlay(),play(),Grow(),checkGrow()等公有的抽象方法。
    (2)構造了抽象類 Animal 類,實現了AnimalInterface接口,擁有種類(animalType)、名稱(name)、買入價值(value_get)、賣出價值(value_sell)、成長值(growthValue)、canSell(能否賣出)屬性,擁有吃東西(eat),喝水(drink),和主人玩(play),增加成長值(grow)以及一些get與set的實現了封裝性的方法。
    (3)定義了Cat類,Dog類,Rabbit類,Tiger類,繼承了Animal類,然後具體實現各自的細節,因此程序具有良好的拓展性,想要增加遊戲內容只需根據Animal類增添新的動物類即可。
    (4)構造了Farmer類,擁有姓名(name)、養的寵物(Animal[] animals)、擁有的寵物數量(animalCount)、擁有金錢(money)屬性,擁有和寵物玩(playWithAnimal),買寵物(buyAnimal),賣寵物(sellAnimal),查看狀態(showAll)以及一些get與set的實現了封裝性的方法。
  6. 構造了管理遊戲語言描述的類WordManage,在這裏用public static final 定義了公有靜態常量,遊戲中用到時直接調用即可,當要修改遊戲內描述時只需要來WordManage類修改即可,十分方便。
  7. 利用了Animal類數組存放了Animal的對象,對數組與類着有深刻的理解。
  8. 靈活運用了順序、選擇、循環的結構,程序結構清晰,條理明確。
  9. 對於程序有良好的註釋習慣,程序的可讀性十分高。
  10. 利用異常處理,對程序數據錯誤的情況進行了恰當的處理。

運行截圖

開始運行程序(此時遊戲未開始)
在這裏插入圖片描述
開始遊戲前點擊任何功能按鍵都無效,彈框提示開始遊戲。
在這裏插入圖片描述點擊【遊戲開始】,提示輸入姓名,創建角色。
在這裏插入圖片描述
角色創建成功,初始金錢 200
在這裏插入圖片描述
【購買寵物】,目前可以購買的寵物有【狗】、【貓】、【兔子】、【老虎】、【陸振宇】(最後一個什麼鬼,彩蛋~),價格分別爲 60,100,150,250,賣出價格則是翻倍,代碼有良好的拓展性,所以在定義了規範後增加新的寵物是很簡單的。現在,我們買一隻貓。
在這裏插入圖片描述

輸入寵物名稱【大花】,如果錢足夠則購買成功。在這裏插入圖片描述
錢足夠,購買成功。
在這裏插入圖片描述
對寵物進行操作需要選中寵物,否則會跳出提示。
在這裏插入圖片描述
選中購買的寵物。
在這裏插入圖片描述
在這裏插入圖片描述在這裏插入圖片描述
在這裏插入圖片描述
分別點擊【餵食寵物】,【寵物喝水】,【陪玩寵物】,會增加寵物成長值。
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
當寵物成長值>=50,則可以出售,賺更多的錢。
在這裏插入圖片描述
錢不夠則無法購買寵物。
在這裏插入圖片描述

源代碼

animal 包

AnimalInterface.java

/*
 * 動物接口
 */
public interface AnimalInterface {
	public abstract String eat();		// 吃東西
	public abstract String drink();		// 喝水
	public abstract String wantPlay();	// 想要玩
	public abstract String play();		// 和主人玩
	public abstract String grow(int value);// 成長
	public abstract int checkGrow();	// 查看成長值
}

Animal.java

/*
* 動物抽象類,實現動物接口
*/
public abstract class Animal implements AnimalInterface {
   String animalType;	// 種類
   String name;		// 名稱
   float value_get = 100;	// 買入價值
   float value_sell = 80;	// 賣出價值
   boolean canSell = false; // 能否賣出,默認不能賣出
   /*
    *  成長值,當成長值 >= 50,可以售賣
    *  初始成長值爲 1 
    *  每次陪它玩,成長值 + 6
    *  吃東西,成長值 + 8
    *  喝水,成長值 + 4
    */
   int growthValue = 0;
   
   public String eat() {		// 吃東西
   	System.out.println(this.name  + "吃了點東西,吃的好飽呀!");
   	grow(8);	// 增加成長值
   	return this.name  + "吃了點東西,吃的好飽呀!(成長值+8)";
   };
   public String drink(){		// 喝水
   	System.out.println(this.name + "喝了點水,一點也不可渴了!");
   	grow(4);	// 增加成長值
   	return this.name + "喝了點水,一點也不可渴了!";
   };
   public String play(){		// 和主人玩
   	System.out.println(this.name + "和你玩了一會兒,看起來十分開心!");
   	grow(6);	// 增加成長值
   	return this.name + "和你玩了一會兒,看起來十分開心!";
   }
   public String wantPlay(){	// 想要玩
   	System.out.println(this.name + "看着你,似乎想要你和它玩。");
   	return this.name + "看着你,似乎想要你和它玩。";
   }
   /*
    * grow(Animal animal, int value) 爲優化後的代碼,更好的利用了繼承
    * grow(int value) 可以不需要了
    */
   public static String grow(Animal animal, int value){	// 增加成長值
   	animal.setGrowthValue(animal.getGrowthValue() + value);
   	System.out.println(animal.getName() +"的成長值增加了" + value);
   	checkGrow(animal);
   	return animal.getName() +"的成長值增加了" + value;
   }
   public String grow(int value){	// 增加成長值
   	this.growthValue += value;
   	System.out.println(this.name + "的成長值加了" + value);
   	return this.name + "的成長值加了" + value;	// 增加成長值
   }
   /*
    * checkGrow(Animal animal) 爲優化後的代碼,更好的利用繼承
    * checkGrow() 可以不需要了
    */
   static int checkGrow(Animal animal){	// 檢測成長值
   	if (!animal.isCanSell()) {
   		if (animal.getGrowthValue() >= 50) {
   			animal.setCanSell(true);
   			System.out.println("@@@這隻動物已經可以賣掉啦!@@@");
   			return animal.getGrowthValue();
   		}else{
   			return animal.getGrowthValue();
   		}
   	}
   	return animal.getGrowthValue();
   }
   public int checkGrow(){	// 每回合檢測成長值
   	if (!canSell) {	// 不能賣出時檢測,可以賣了則不用檢測
   		if (this.growthValue >= 50) {
   			canSell = true; // 此時可以賣出了。
   			System.out.println("這隻動物已經可以賣掉啦!");
   			return this.growthValue;
   		}else{
   			return this.growthValue;
   		}
   	}
   	return growthValue;
   }
   
   public String getAnimalType() {
   	return animalType;
   }
   public void setAnimalType(String animalType) {
   	this.animalType = animalType;
   }
   public String getName() {
   	return name;
   }
   public void setName(String name) {
   	this.name = name;
   }
   public float getValue_get() {
   	return value_get;
   }
   public void setValue_get(float value_get) {
   	this.value_get = value_get;
   }
   public float getValue_sell() {
   	return value_sell;
   }
   public void setValue_sell(float value_sell) {
   	this.value_sell = value_sell;
   }
   public boolean isCanSell() {
   	return canSell;
   }
   public void setCanSell(boolean canSell) {
   	this.canSell = canSell;
   }
   public int getGrowthValue() {
   	return growthValue;
   }
   public void setGrowthValue(int growthValue) {
   	this.growthValue = growthValue;
   }
}

Dog.java

/*
 * 動物類的子類,狗類
 */
public class Dog extends Animal {
	private String animalType = "狗";
	private String name = "小狗";
	private float value_get = 60; 	// 買入價格
	private float value_sell = 120; // 賣出價格
	private int growthValue = 0;	// 默認成長值爲0
	private boolean canSell = false;// 能否出售

	public Dog() {};
	public Dog(String name){
		this.name = name;
	}
	public Dog(String animalType, String name, float value_get, float value_sell) {
		super();
		this.animalType = animalType;
		this.name = name;
		this.value_get = value_get;
		this.value_sell = value_sell;
	}

	public String eat() {	// 狗狗吃東西
		System.out.println(this.name  + WordManage.eatDescribe + WordManage.dogWord);
		grow(this, 8);	// 增加成長值
//		checkGrow(this);
		return this.name  + WordManage.eatDescribe + WordManage.dogWord;
	}

	public String drink() {	// 狗狗喝水
		System.out.println(this.name + WordManage.drinkDescribe + WordManage.dogWord);
		grow(this, 4);	// 增加成長值
//		checkGrow(this);
		return this.name + WordManage.drinkDescribe + WordManage.dogWord;
	}

	public String play() {	// 狗狗和主人玩
		System.out.println(this.name + WordManage.playDescribe + WordManage.dogWord);
		grow(this, 6);	// 增加成長值
//		checkGrow(this);
		return this.name + WordManage.playDescribe + WordManage.dogWord;
	}
	
	public String wantPlay() {	// 狗狗想玩
		System.out.println(this.name + "搖着尾巴看着你,好像希望你陪它玩!");
		return this.name + "搖着尾巴看着你,好像希望你陪它玩!";
	}

	public String getAnimalType() {
		return animalType;
	}
	public void setAnimalType(String animalType) {
		this.animalType = animalType;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public float getValue_get() {
		return value_get;
	}
	public void setValue_get(float value_get) {
		this.value_get = value_get;
	}
	public float getValue_sell() {
		return value_sell;
	}
	public void setValue_sell(float value_sell) {
		this.value_sell = value_sell;
	}
	public int getGrowthValue() {
		return growthValue;
	}
	public void setGrowthValue(int growthValue) {
		this.growthValue = growthValue;
	}
	public boolean isCanSell() {
		return canSell;
	}
	public void setCanSell(boolean canSell) {
		this.canSell = canSell;
	}
	@Override
	public String toString() {
		return "【狗】" + name;
	}
	
}

Cat.java

/*
 * 動物類的子類,貓類
 */
public class Cat extends Animal{
	private String animalType = "貓";
	private String name = "貓咪";
	private float value_get = 100; 	// 買入價格
	private float value_sell = 200; // 賣出價格
	private int growthValue = 0;	// 默認成長值爲0
	private boolean canSell = false;// 能否出售
	
	public Cat(){};
	public Cat(String name){
		this.name = name;
	}
	
	public String eat(){	// 貓吃東西
		System.out.println(this.name + WordManage.eatDescribe + WordManage.catWord);
		grow(this, 8);
		return this.name + WordManage.eatDescribe + WordManage.catWord;
	}
	
	public String drink(){	// 貓喝水
		System.out.println(this.name + WordManage.drinkDescribe + WordManage.catWord);
		grow(this, 4);	// 增加成長值
		return this.name + WordManage.drinkDescribe + WordManage.catWord;
	}
	
	public String play(){	// 貓和主人玩
		System.out.println(this.name + WordManage.playDescribe + WordManage.catWord);
		grow(this, 6);	// 增加成長值
		return this.name + WordManage.playDescribe + WordManage.catWord;
	}
	
	public String wantPlay(){	// 貓想玩
		System.out.println(this.name + "瞪大了眼睛看着你,好像希望你能陪它玩!");
		return this.name + "瞪大了眼睛看着你,好像希望你能陪它玩!";
	}
	
	public String getAnimalType() {
		return animalType;
	}
	public void setAnimalType(String animalType) {
		this.animalType = animalType;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public float getValue_get() {
		return value_get;
	}
	public void setValue_get(float value_get) {
		this.value_get = value_get;
	}
	public float getValue_sell() {
		return value_sell;
	}
	public void setValue_sell(float value_sell) {
		this.value_sell = value_sell;
	}
	public int getGrowthValue() {
		return growthValue;
	}
	public void setGrowthValue(int growthValue) {
		this.growthValue = growthValue;
	}
	public boolean isCanSell() {
		return canSell;
	}
	public void setCanSell(boolean canSell) {
		this.canSell = canSell;
	}
	@Override
	public String toString() {
		return "【貓】" + name;
	}
	
}

Rabbit.java

/*
 * 動物類的子類,兔子類
 */
public class Rabbit extends Animal{
	private String animalType = "兔子";
	private String name = "小白兔";
	private float value_get = 150; 	// 買入價格
	private float value_sell = 300; // 賣出價格
	private int growthValue = 0;	// 默認成長值爲0
	private boolean canSell = false;// 能否出售

	public Rabbit() {};
	public Rabbit(String name){
		this.name = name;
	}

	public String eat() {	// 兔子吃東西
		System.out.println(this.name  + WordManage.eatDescribe + WordManage.rabbitWord);
		grow(this, 8);	// 增加成長值
		return this.name  + WordManage.eatDescribe + WordManage.rabbitWord;
	}

	public String drink() {	// 兔子喝水
		System.out.println(this.name + WordManage.drinkDescribe + WordManage.rabbitWord);
		grow(this, 4);	// 增加成長值
		return this.name + WordManage.drinkDescribe + WordManage.rabbitWord;
	}

	public String play() {	// 兔子和主人玩
		System.out.println(this.name + WordManage.playDescribe + WordManage.rabbitWord);
		grow(this, 6);	// 增加成長值
		return this.name + WordManage.playDescribe + WordManage.rabbitWord;
	}
	
	public String wantPlay() {	// 兔子想玩
		System.out.println(this.name + "在你周圍蹦來蹦去,好像希望你陪它玩!");
		return this.name + "在你周圍蹦來蹦去,好像希望你陪它玩!";
	}

	public String getAnimalType() {
		return animalType;
	}
	public void setAnimalType(String animalType) {
		this.animalType = animalType;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public float getValue_get() {
		return value_get;
	}
	public void setValue_get(float value_get) {
		this.value_get = value_get;
	}
	public float getValue_sell() {
		return value_sell;
	}
	public void setValue_sell(float value_sell) {
		this.value_sell = value_sell;
	}
	public int getGrowthValue() {
		return growthValue;
	}
	public void setGrowthValue(int growthValue) {
		this.growthValue = growthValue;
	}
	public boolean isCanSell() {
		return canSell;
	}
	public void setCanSell(boolean canSell) {
		this.canSell = canSell;
	}
	@Override
	public String toString() {
		return "【兔子】" + name;
	}
	
}

Tiger.java

/*
 * 動物類的子類,老虎類
 */
public class Tiger extends Animal{
	private String animalType = "老虎";
	private String name = "大老虎";
	private float value_get = 250; 	// 買入價格
	private float value_sell = 500; // 賣出價格
	private int growthValue = 0;	// 默認成長值爲0
	private boolean canSell = false;// 能否出售

	public Tiger() {};
	public Tiger(String name){
		this.name = name;
	}

	public String eat() {	// 老虎吃東西
		System.out.println(this.name  + WordManage.eatDescribe + WordManage.tigerWord);
		grow(this, 8);	// 增加成長值
		return this.name  + WordManage.eatDescribe + WordManage.tigerWord;
	}

	public String drink() {	// 兔子喝水
		System.out.println(this.name + WordManage.drinkDescribe + WordManage.tigerWord);
		grow(this, 4);	// 增加成長值
		return this.name + WordManage.drinkDescribe + WordManage.tigerWord;
	}

	public String play() {	// 兔子和主人玩
		System.out.println(this.name + WordManage.playDescribe + WordManage.tigerWord);
		grow(this, 6);	// 增加成長值
		return this.name + WordManage.playDescribe + WordManage.tigerWord;
	}
	
	public String wantPlay() {	// 兔子想玩
		System.out.println(this.name + "充滿威嚴的盯着你看,好像希望你陪它玩(應該不是想吃了你)!");
		return this.name + "充滿威嚴的盯着你看,好像希望你陪它玩(應該不是想吃了你)!";
	}

	public String getAnimalType() {
		return animalType;
	}
	public void setAnimalType(String animalType) {
		this.animalType = animalType;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public float getValue_get() {
		return value_get;
	}
	public void setValue_get(float value_get) {
		this.value_get = value_get;
	}
	public float getValue_sell() {
		return value_sell;
	}
	public void setValue_sell(float value_sell) {
		this.value_sell = value_sell;
	}
	public int getGrowthValue() {
		return growthValue;
	}
	public void setGrowthValue(int growthValue) {
		this.growthValue = growthValue;
	}
	public boolean isCanSell() {
		return canSell;
	}
	public void setCanSell(boolean canSell) {
		this.canSell = canSell;
	}
	@Override
	public String toString() {
		return "【老虎】" + name;
	}

}

player 包

Farmer.java

/*
 * 農場主類
 */
public class Farmer {
	private String name = "主人";		
	Animal[] animals = null;	// 養的寵物們
	// private Animal animal = null;// 養的寵物
	private int animalCount = 0;	// 擁有寵物的數量
	private float money = 200;		// 擁有金錢
	
	public Farmer(){}
	public Farmer(String name) {
		this.name = name;
	}
	
	public String playWithAnimal(Animal animal){	// 和某個寵物玩
		return animal.play();
	}
	
	public String sellAnimal(Animal animal){	// 把寵物賣了
		if (animal.isCanSell()) {	// 如果可以賣
			System.out.println(this.name + "把" + animal.getName() + "賣掉了,賺了" + animal.getValue_sell() + "元!");
			this.animalCount--;	// 寵物數量-1
			for(int i = 0 ; i < animals.length ; i++){	// 寵物賣掉了!
				if (animals[i].getName().equals(animal.getName())) {
					animals[i] = null;
					break;
				}
			}
			this.money += animal.getValue_sell();
			return this.name + "把" + animal.getName() + "賣掉了,賺了" + animal.getValue_sell() + "元!";
		}else {	// 還不能賣
			System.out.println(animal.getName() + "目前的成長值只有" + animal.getGrowthValue() + ",還不能賣!");
			return animal.getName() + "目前的成長值只有" + animal.getGrowthValue() + ",還不能賣!";
		}
	}
	
	public boolean canBuy(Animal animal){	// 是否買得起
		if (this.money >= animal.getValue_get()) {
			return true;
		}else{
			return false;
		}
	}
	public String buyAnimal(Animal animal){	// 購買寵物
		if(animals == null){
			animals = new Animal[100];	// 開始養寵物之路
		}
		
		if (canBuy(animal)) {	// 買得起
			for (Animal myAnimal : animals) {
				if (myAnimal == null) {	// 遇到空,跳出
					break;
				}
				if (myAnimal == animal) {	// 同一只寵物
					System.out.println("這隻寵物已經買過了呀!");
					return "這隻寵物已經買過了呀!";
				}
				if (myAnimal.getName() == animal.getName() ) {	// 同名
					System.out.println("已經有這個名字的寵物了!");
					return "已經有這個名字的寵物了!";
				}
			}
			
			System.out.println(this.name + "買了一隻" + animal.getAnimalType() + ",花費了" + animal.getValue_get() + "元,剩餘" + (this.money-animal.getValue_get()) + "元。");
			this.money -= animal.getValue_get();
			this.animals[animalCount] = animal;	// 養的寵物增加
			this.animalCount++;	// 寵物數量+1
			return this.name + "買了一隻" + animal.getAnimalType() + ",花費了" + animal.getValue_get() + "元,剩餘" + this.money + "元。";
		}else{	// 買不起
			System.out.println("對不起,餘額不足,無法購買!");
			return "對不起,餘額不足,無法購買!";
		}
	}
	
	public String showAll(){
		System.out.println("********************");
		System.out.println(this.name + "目前有" + this.animalCount + "只寵物。");
		System.out.println(this.name + "目前有" + this.money + "元。");
		System.out.println(this.name + "目前寵物信息:");
		if (animals!=null) {
			for (Animal animal : animals) {
				if(animal == null){
					break;
				}
				System.out.println(animal.getName() + "的成長值爲" + animal.getGrowthValue() + "。");
			}
		}else {
			System.out.println("目前沒有寵物!");
		}
		System.out.println("********************");
		
		StringBuilder content = new StringBuilder();
		content.append("****************\n");
		content.append("【" + this.name + "】\n");
		content.append("寵物數量:" + this.animalCount + "只。\n");
		
		content.append("金錢數量:" + this.money + "元。\n");
		content.append("寵物信息:\n");
		if (animals!=null) {
			for (Animal animal : animals) {
				if(animal == null){
					break;
				}
				content.append(animal.getName() + "的成長值:" + animal.getGrowthValue() + "。\n");
			}
		}else {
			content.append("目前沒有寵物!");
		}
		content.append("****************\n");
		return content+"";
	}
	
	public String feedAnimal(Animal animal){	// 喂寵物
		return animal.eat();
	}
	
	public String giveWater(Animal animal){	// 給動物水喝
		return animal.drink();
	}

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Animal[] getAnimals() {
		return animals;
	}
	public void setAnimals(Animal[] animals) {
		this.animals = animals;
	}
	public int getAnimalCount() {
		return animalCount;
	}
	public void setAnimalCount(int animalCount) {
		this.animalCount = animalCount;
	}
	public float getMoney() {
		return money;
	}
	public void setMoney(float money) {
		this.money = money;
	}
	
}

Scene 包

Ranch.java

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceDialog;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextInputDialog;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import 趙鉞.animal.Animal;
import 趙鉞.animal.Cat;
import 趙鉞.animal.Dog;
import 趙鉞.animal.Rabbit;
import 趙鉞.animal.Tiger;
import 趙鉞.player.Farmer;
/*
 * 場景:牧場
 */
public class Ranch extends javafx.application.Application {
	private Label stateFrame = new Label(
			"\t 歡   雖   依\n\t 迎   然   舊\n\t 來   目   祝\n\t 到   前   你\n\t 牧   是   遊\n\t 場   測   玩\n\t 物   試   愉\n\t 語   版   快\n\t");
	ObservableList<Animal> list = FXCollections.observableArrayList();
	private ListView<Animal> listView = new ListView<>(list); // 顯示寵物的列表
	private Button buttonBuy = new Button("購買寵物");
	private Button buttonSell = new Button("出售寵物");
	private Button buttonFeed = new Button("餵食寵物");
	private Button buttonDrink = new Button("寵物喝水");
	private Button buttonPlay = new Button("陪玩寵物");
	private Button buttonStart = new Button("遊戲開始");
	private Label gameFrame = new Label(); // 中間遊戲界面
	private Label gameDescribe = new Label("歡迎來到牧場物語,你可以在這裏購買寵物,餵養寵物,售賣寵物,以此獲取金錢,然後購買新的寵物。當你擁有一定數量的寵物後遊戲纔會結束,盡情的享受牧場生活吧!"); // 遊戲描述
	private boolean isStarted = false; // 遊戲是否開始
	Farmer player; // 聲明用戶,但是等點擊遊戲開始再初始化

	@Override
	public void start(Stage primaryStage) throws Exception {
		listView.setPrefSize(145, 328); // 設置列表視圖的寬、高
		// listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); // 多選模式

		BorderPane borderPane = new BorderPane(); // 邊界面板

		/*************** 左邊 **************************/
		borderPane.setLeft(new ScrollPane(listView)); // 左邊顯示擁有的寵物列表
		borderPane.setPadding(new Insets(10, 0, 0, 10));

		/*************** 右邊 **************************/
		stateFrame.setPrefSize(200, 440); // 右邊玩家狀態
		stateFrame.setTextFill(javafx.scene.paint.Color.BLUE);
		stateFrame.setFont(new Font("Cambria", 19));
		stateFrame.setWrapText(true); // 自動換行
		borderPane.setRight(stateFrame);

		/*************** 中間 **************************/
		Image imageBag = new Image("backg2.png");
		ImageView bagImageView = new ImageView();
		bagImageView.setImage(imageBag);
		bagImageView.setFitWidth(410);
		bagImageView.setPreserveRatio(true); // 按比例縮放
		gameFrame.setGraphic(bagImageView);
		borderPane.setCenter(gameFrame); // 中間

		/*************** 底下 **************************/
		FlowPane buttonPane = new FlowPane(2, 2);
		borderPane.setBottom(buttonPane);
		gameDescribe.setPrefSize(700, 60); // 遊戲描述
		buttonPane.getChildren().add(gameDescribe);
		gameDescribe.setTextFill(Color.RED);
		gameDescribe.setFont(new Font("Cambria", 18));
		gameDescribe.setWrapText(true); // 自動換行

		buttonPane.setOrientation(Orientation.HORIZONTAL); // 設置節點水平擺放
		buttonPane.setPadding(new Insets(12, 13, 14, 15)); // 設置面板邊緣內測四周空白的距離
		buttonPane.setHgap(40); // 設置面板上節點之間的水平間距爲40像素
		buttonPane.setVgap(5); // 設置面板上節點之間的垂直間距爲5像素
		buttonPane.getChildren().add(buttonBuy);
		buttonPane.getChildren().add(buttonSell);
		buttonPane.getChildren().add(buttonFeed);
		buttonPane.getChildren().add(buttonDrink);
		buttonPane.getChildren().add(buttonPlay);
		buttonPane.getChildren().add(buttonStart);

		/************************ 點擊事件 ***********************/
		// 開始遊戲
		buttonStart.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent event) {
				if (!isStarted) { // 若遊戲還未開始,提示開始遊戲
					TextInputDialog dialog = new TextInputDialog("振宇"); // 默認用戶名
					dialog.setTitle("創建角色");
					dialog.setHeaderText(null);
					dialog.setContentText("請輸入你的姓名:");
					Optional<String> result = dialog.showAndWait();
					if (result.isPresent()) { // 輸入名字後,創建角色,開始遊戲
						String name = result.get();
						player = new Farmer(name);
						stateFrame.setText(player.showAll());
						isStarted = true;
					}
				} else { // 若遊戲已經開始,提示已經在遊戲
					Alert alert = new Alert(AlertType.INFORMATION);
					alert.setTitle("提示框");
					alert.setHeaderText(null);
					alert.setContentText("你已經開始遊戲了呀!");
					alert.showAndWait();
				}
			}
		});
		// 購買寵物
		buttonBuy.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent event) {
				if (!isStarted) { // 未開始遊戲
					Alert alert = new Alert(AlertType.INFORMATION);
					alert.setTitle("提示框");
					alert.setHeaderText(null);
					alert.setContentText("你倒是先開始遊戲啊!");
					alert.showAndWait();
				} else { // 遊戲中
					List<String> choices = new ArrayList<>();
					choices.add("狗");
					choices.add("貓");
					choices.add("兔子");
					choices.add("老虎");
					choices.add("陸振宇");
				    /* ...........
					 * 此處可以繼續拓展
					 */
						
					ChoiceDialog<String> dialog = new ChoiceDialog<>("狗", choices);
					dialog.setTitle("購買寵物");
					dialog.setHeaderText(null);
					dialog.setContentText("選擇你要購買的寵物:");
					Optional<String> result = dialog.showAndWait();
					if (result.isPresent()) {
						String animalType = result.get();
						switch (animalType) {
							case "狗": {
								TextInputDialog dialog2 = new TextInputDialog("小狗");
								dialog2.setTitle("寵物取名");
								dialog2.setHeaderText(null);
								dialog2.setContentText("請輸入寵物名稱:");
								result = dialog2.showAndWait();
								if (result.isPresent()) {
									Dog dog = new Dog(result.get());
									if (player.canBuy(dog)) { // 買得起纔買
										gameDescribe.setText(player.buyAnimal(dog));
										list.add(dog);
									}else{
										Alert alert = new Alert(AlertType.WARNING);
										alert.setTitle("錯誤提示");
										alert.setHeaderText(null);
										alert.setContentText("餘額不足,無法購買!");
										alert.showAndWait();
									}
								}
								break;
							}
							case "貓": {
								TextInputDialog dialog2 = new TextInputDialog("喵咪");
								dialog2.setTitle("寵物取名");
								dialog2.setHeaderText(null);
								dialog2.setContentText("請輸入寵物名稱:");
								result = dialog2.showAndWait();
								if (result.isPresent()) {
									Cat cat = new Cat(result.get());
									if (player.canBuy(cat)) { // 買得起纔買
										gameDescribe.setText(player.buyAnimal(cat));
										list.add(cat);
									}else{
										Alert alert = new Alert(AlertType.WARNING);
										alert.setTitle("錯誤提示");
										alert.setHeaderText(null);
										alert.setContentText("餘額不足,無法購買!");
										alert.showAndWait();
									}
								}
								break;
							}
							case "兔子": {
								TextInputDialog dialog2 = new TextInputDialog("兔兔");
								dialog2.setTitle("寵物取名");
								dialog2.setHeaderText(null);
								dialog2.setContentText("請輸入寵物名稱:");
								result = dialog2.showAndWait();
								if (result.isPresent()) {
									Rabbit rabbit = new Rabbit(result.get());
									if (player.canBuy(rabbit)) { // 買得起纔買
										gameDescribe.setText(player.buyAnimal(rabbit));
										list.add(rabbit);
									}else{
										Alert alert = new Alert(AlertType.WARNING);
										alert.setTitle("錯誤提示");
										alert.setHeaderText(null);
										alert.setContentText("餘額不足,無法購買!");
										alert.showAndWait();
									}
								}
							}
							case "老虎": {
								TextInputDialog dialog2 = new TextInputDialog("阿虎");
								dialog2.setTitle("寵物取名");
								dialog2.setHeaderText(null);
								dialog2.setContentText("請輸入寵物名稱:");
								result = dialog2.showAndWait();
								if (result.isPresent()) {
									Tiger tiger = new Tiger(result.get());
									if (player.canBuy(tiger)) { // 買得起纔買
										gameDescribe.setText(player.buyAnimal(tiger));
										list.add(tiger);
									}else{
										Alert alert = new Alert(AlertType.WARNING);
										alert.setTitle("錯誤提示");
										alert.setHeaderText(null);
										alert.setContentText("餘額不足,無法購買!");
										alert.showAndWait();
									}
								}
								break;
							}
							case "陸振宇":{
								Alert alert = new Alert(AlertType.WARNING);
								alert.setTitle("錯誤提示");
								alert.setHeaderText("你怕是在搞蛇皮。");
								alert.setContentText("你是在想什麼呢!小老弟?");
								alert.showAndWait();
								break;
							}
						}
					}
					stateFrame.setText(player.showAll()); // 刷新界面
				}
			}
		});
		// 賣寵物
		buttonSell.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent event) {
				if (!isStarted) {	// 遊戲未開始
					Alert alert = new Alert(AlertType.INFORMATION);
					alert.setTitle("提示框");
					alert.setHeaderText(null);
					alert.setContentText("你倒是先開始遊戲啊!");
					alert.showAndWait();
				} else {	// 遊戲中
					try{
						if (listView.getSelectionModel().getSelectedItem().isCanSell()) {
							gameDescribe.setText(player.sellAnimal(listView.getSelectionModel().getSelectedItem()));
							showMessage("你把" +listView.getSelectionModel().getSelectedItem().getName()+"賣掉了!" );
							list.remove(listView.getSelectionModel().getSelectedItem());
						}else{
							showMessage(listView.getSelectionModel().getSelectedItem().getName()+"目前的成長值只有"
									+ listView.getSelectionModel().getSelectedItem().getGrowthValue()+",還不能賣!\n"
									+ "(成長值>=50纔可以賣)");
						}
					}catch (Exception e) {
						showMessage("你倒是選擇你要賣的寵物啊!");
					}finally{
						stateFrame.setText(player.showAll()); // 刷新界面
					}
				}
			}
		});
		// 給寵物餵食
		buttonFeed.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent event) {
				if (!isStarted) {	// 遊戲未開始
					Alert alert = new Alert(AlertType.INFORMATION);
					alert.setTitle("提示框");
					alert.setHeaderText(null);
					alert.setContentText("你倒是先開始遊戲啊!");
					alert.showAndWait();
				} else {	// 遊戲中
					try{
						gameDescribe.setText(player.feedAnimal(listView.getSelectionModel().getSelectedItem()));
					}catch (Exception e) {
						showMessage("你倒是選擇你要餵食的寵物啊!");
					}finally{
						stateFrame.setText(player.showAll()); // 刷新界面
					}
				}
			}
		});
		// 給寵物喝水
		buttonDrink.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent event) {
				if (!isStarted) {	// 遊戲未開始
					Alert alert = new Alert(AlertType.INFORMATION);
					alert.setTitle("提示框");
					alert.setHeaderText(null);
					alert.setContentText("你倒是先開始遊戲啊!");
					alert.showAndWait();
				} else {	// 遊戲中
					try{
						gameDescribe.setText(player.giveWater(listView.getSelectionModel().getSelectedItem()));
					}catch (Exception e) {
						showMessage("你倒是選擇你要給哪隻寵物喝水啊!");
					}finally{
						stateFrame.setText(player.showAll()); // 刷新界面
					}
				}
			}
		});
		// 陪寵物玩
		buttonPlay.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent event) {
				if (!isStarted) {	// 遊戲未開始
					Alert alert = new Alert(AlertType.INFORMATION);
					alert.setTitle("提示框");
					alert.setHeaderText(null);
					alert.setContentText("你倒是先開始遊戲啊!");
					alert.showAndWait();
				} else {	// 遊戲中
						try{
							gameDescribe.setText(player.playWithAnimal(listView.getSelectionModel().getSelectedItem()));
						}catch (Exception e) {
							showMessage("你到是選擇你要陪哪隻寵物玩啊!");
						}finally {
							stateFrame.setText(player.showAll()); // 刷新界面
					}
				}
			}
		});
		// 點擊列表,中間顯示圖片
		listView.getSelectionModel().selectedItemProperty().addListener(ov -> {
			System.out.println(listView.getSelectionModel().getSelectedIndex()); // 獲取選擇元素的下標
			System.out.println(listView.getSelectionModel().getSelectedItem().getName());// 獲取選擇元素Item
			switch (listView.getSelectionModel().getSelectedItem().getAnimalType()) {
				case "狗": {
					setPicture(gameFrame, "dog.png", 300);
					break;
				}
				case "貓": {
					setPicture(gameFrame, "cat.png", 260);
					break;
				}
				case "兔子": {
					setPicture(gameFrame, "rabbit.png", 192);
					break;
				}
				case "老虎": {
					setPicture(gameFrame, "tiger.png", 196);
					break;
				}
			}
		});

		Scene scene = new Scene(borderPane, 730, 450);
		primaryStage.setResizable(false);  // 窗口設定爲不可調整
		primaryStage.setTitle("振宇的牧場物語");
		primaryStage.setScene(scene);
		primaryStage.show();
	}

	// 封裝的標籤設置圖片方法
	public void setPicture(Label label, String picName, int size) {
		Image image = new Image(picName);
		ImageView imageView = new ImageView();
		imageView.setImage(image);
		imageView.setPreserveRatio(true); // 保持縮放比例
		imageView.setFitWidth(size); // 設置寬度
		imageView.setSmooth(true); // 設置圓滑
		imageView.setCache(true); // 設置緩衝
		label.setGraphic(imageView);
	}
	// 封裝的談對話框方法
	public void showMessage(String showStr){
		Alert alert = new Alert(AlertType.INFORMATION);
		alert.setTitle("提示框");
		alert.setHeaderText(null);
		alert.setContentText(showStr);
		alert.showAndWait();
	}
	public static void main(String[] args) {
		launch(args);
	}
}

Util 包

WordManage.java

/*
 * 語言管理類,方便管理文字
 */
public class WordManage {
	// 通用
	public static final String eatDescribe= "吃了點東西,吃的好飽呀,";		// 吃
	public static final String drinkDescribe = "喝了幾口水,一點也不渴了,";	// 喝
	public static final String playDescribe = "和你玩了一會兒,";			// 玩
	// 狗
	public static final String dogWord = "高興地“汪汪”了兩聲!(成長值增加了!)";
	// 貓
	public static final String catWord = "開心地“喵喵”叫了幾聲!(成長值增加了!)";
	// 兔
	public static final String rabbitWord= "高興的蹦來蹦去!(成長值增加了!)";
	// 虎
	public static final String tigerWord = "嗷~~的吼了幾聲!(成長值增加了!)";
}

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