I am a Java programmer, and I just recently started learning Scala for fun. I found a group of projects here, and I tried to do the graduation excercise. The problem is, my code looks a lot like java, and I want to make this code more styled to fit scala, though I'm not sure what that entails. (Making it more functional?)
This is my main game class:
object Game {
def main(args: Array[String]): Unit = {
val list : ListBuffer[Bunny] = ListBuffer.fill(5)(BunnyFactory.getInitial)
while(list.size != 0){
var iterator = 0;
//make sure we have one male for mating
var males = 0;
//keep track of females for mating
var females : ListBuffer[Bunny] = new ListBuffer
for(i <- list){
i.update(list)
if(i.dead){
println(s"Bunny ${i.name} died at age ${i.age}!")
list.remove(iterator)
}
else {
if(i.gender == Gender.Male && i.adult){
males += 1;
}else if (i.gender == Gender.Female && i.adult){
females += i;
}
println(i)
}
iterator += 1;
}
if(males >= 1){
for(i <- females){
val child = BunnyFactory.getChild(i);
println(s"Bunny ${child.name} was born!")
list += child
}
}
println(s"There are ${list.size} bunnies!")
Thread.sleep(500)
}
}
}
My Bunny class (I'm not sure if my variable naming follows conventions here):
class Bunny(inColor : Color.Value, inGender : Gender.Value, inAge : Int, inName : String, radioactive : Boolean){
private val _color = inColor;
private val _gender = inGender;
private val _name = inName;
private var _radioactive = radioactive;
private var _age = inAge;
def gender = _gender
def age = _age
def name = _name
def adult : Boolean = {_age >= 2 && !(_radioactive)}
def color = _color
def dead : Boolean = {
if(_radioactive){
_age > 50;
}else{
_age > 10;
}
}
def infect : Unit = {_radioactive = true}
def update(list : ListBuffer[Bunny]) : Unit = {
_age += 1
if(_radioactive){
list((Math.random() * list.length).toInt).infect
}
}
override def toString() : String = {
return s"${_color} ${_gender} Bunny ${_name}, ${_age} years old, Radioactive: ${_radioactive}"
}
}
Bunny Factory class:
object BunnyFactory {
def getInitial : Bunny = {
return new Bunny(
Color.getRandom,
Gender.getRandom,
0,
getName,
false)
}
def getChild(mom : Bunny) : Bunny = {
val rand = (Math.random() * 100).toInt
return new Bunny(mom.color, Gender.getRandom, 0, getName, rand <= 2)
}
val names : ListBuffer[String] = {
val source = Source.fromFile("res/names.txt")
val lines : List[String] = source.getLines.toList
source.close
lines.to[ListBuffer]
}
def getName : String = {
val rand = (Math.random() * names.size).toInt
return names(rand)
}
}
Gender object:
object Gender extends Enumeration{
type Gender = Value
val Male, Female = Value
def getRandom() : Gender = {
val rand : Int = (Math.random() * values.size).toInt
return this.apply(rand)
}
}
Color object:
object Color extends Enumeration{
type Color = Value
val White, Brown, Black, Spotted = Value
def getRandom() : Color = {
val rand : Int = (Math.random() * values.size).toInt
return this.apply(rand)
}
}