所以我正在嘗試創建一個游戲,用戶必須從英雄池中選擇 1 個英雄。我應該如何創建用戶選擇的英雄的物件?基本上我正在嘗試根據用戶輸入創建一個物件
編輯:我意識到僅僅放一段是不夠的,我還應該添加我的代碼結構。目前我有一個英雄類,其他所有英雄都從這個類擴展,所以我正在嘗試做這樣的事情
class Hero {
}
class Bob extends Hero{ //Bob is one of the heroes that the user can choose
def skill1() { //the skills that Bob can use
}
}
class Player() {
val hero //player's hero option will be stored here
}
class Game { //gamedata will be stored here
val player: Player = new Player()
}
class Controller {
def selectHero { //this is where the user inputs a number from 1 to 10 and the app will create a hero object
}
}
我被困在selectHero方法上,不知道如何進行。我試著做這樣的事情:
val _hero1: Hero = (
if (option1 == 1) {
new Bob()
}
else if (option1 == 2) {
new James()
}
else if (option1 == 3) {
new Jimmy()
}
else {
null
}
)
但是我最終無法訪問他們的技能,因為父類無法訪問子類的方法,有人可以幫忙嗎?
uj5u.com熱心網友回復:
這是一個想法:你可以從標準輸入中讀取一個數字并創建任意數量的英雄,直到你想打破回圈。使用繼承和多型,您的呼叫skills()將動態系結到該英雄物件的類。
您可以從這里做很多改進:
- 當
try-catch輸入NumberFormatException不是Int. - 您需要
toString()在擴展的每個類上定義Hero。目前在列印時heroes,我們得到的是物件,而不是它們的字串表示。 - 使用
Hero工廠方法比使用模式匹配更好。 Hero如果類是唯一的,請考慮將它們制作為物件,或者case如果您需要對它們進行模式匹配,請考慮將它們制作為類。
import scala.collection.mutable
import scala.io.StdIn.readLine
import scala.util.control.Breaks.{break, breakable}
object Test extends App {
abstract class Hero {
def skills(): Unit
}
class Bob extends Hero {
def skills(): Unit =
println("This is Bob. His skills are partying like a Hero")
}
class James extends Hero {
def skills(): Unit =
println("This is James. His skills are drinking like a Hero")
}
class Jimmy extends Hero {
def skills(): Unit =
println("This is Jimmy. His skills are gaming like a Hero")
}
object Controller {
def selectHero(option: Int): Hero = option match {
case 1 => new Bob()
case 2 => new James()
case 3 => new Jimmy()
case _ => break
}
}
val heroes = mutable.Set.empty[Hero]
breakable {
while (true) {
val hero = Controller.selectHero(readLine().toInt)
hero.skills()
heroes = hero
}
}
println(heroes)
// process heroes further
println("done")
}
基于輸入的輸出:
1
This is Bob. His skills are partying like a Hero
2
This is James. His skills are drinking like a Hero
3
This is Jimmy. His skills are gaming like a Hero
4
HashSet(Test$James@337d0578, Test$Jimmy@61a485d2, Test$Bob@69d9c55)
done
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/495432.html
標籤:斯卡拉
