因此,我试图创建一个游戏,用户可以选择一个英雄从一个池英雄。我应该如何创建用户选择的英雄的对象?基本上,我试图根据用户的输入创建一个对象。
编辑:我意识到仅仅放一个段落是不够的,我也应该添加我的代码结构。目前我有一个英雄类,其他每个英雄都是从这个类扩展而来的,所以我尝试这样做。
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
}
)但我最终无法获得他们的技能,因为家长班不能访问子类的方法,有人能帮上忙吗?
发布于 2022-06-23 03:39:03
这里有一个想法:您可以从stdin读一个数字,并创建任意数量的英雄,直到您想要打破循环。使用继承和多态性,对skills()的调用将动态绑定到英雄对象的类。
从这里你可以做很多改进:
在输入不是Int.
try-catch块来避免NumberFormatException,需要在每个扩展Hero的类上定义toString()。目前,当我们打印对象时,如果对象是唯一的,则不是它们的字符串representations.
Hero工厂方法会比使用模式match.
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)
donehttps://stackoverflow.com/questions/72723970
复制相似问题