blob: eb1960603c90578f5f31bbea6a687c3c30eeb3e9 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
package o1game.Model
import scala.collection.mutable.Map
/** A `Player` object represents a player character controlled by the real-life user
* of the program.
*
* A player object’s state is mutable: the player’s location and possessions can change,
* for instance.
*
* @param startingArea the player’s initial location */
class Entity(val name: String, initialLocation: Area):
private var currentLocation: Area = initialLocation
private var quitCommandGiven = false // one-way flag
private val inventory: Map[String, Item] = Map()
/** Determines if the player has indicated a desire to quit the game. */
def hasQuit = this.quitCommandGiven // TODO: This is probably unneccessary?
/** Returns the player’s current location. */
def location = this.currentLocation
/** Attempts to move the player in the given direction. This is successful if there
* is an exit from the player’s current location towards the direction name. Returns
* a description of the result: "You go DIRECTION." or "You can't go DIRECTION." */
def go(direction: String) =
val destination = this.location.neighbor(direction)
if destination.isDefined then
this.currentLocation.removeEntity(this.name)
this.currentLocation = destination.getOrElse(this.currentLocation)
destination.foreach(_.addEntity(this))
s"You go $direction."
else
"You can't go " + direction + "."
def pickUp(itemName: String): String =
this.currentLocation.removeItem(itemName) match
case Some(i) =>
this.inventory += i.name -> i
s"You pick up the ${i.name}"
case None => s"There is no $itemName here to pick up."
def drop(itemName: String): String =
this.inventory.remove(itemName) match
case Some(item) =>
this.currentLocation.addItem(item)
s"You drop the $itemName"
case None => "You don't have that!"
/** Causes the player to rest for a short while (this has no substantial effect in game terms).
* Returns a description of what happened. */
def rest() =
"You rest for a while. Better get a move on, though."
/** Signals that the player wants to quit the game. Returns a description of what happened within
* the game as a result (which is the empty string, in this case). */
def quit() =
this.quitCommandGiven = true
""
/** Returns a brief description of the player’s state, for debugging purposes. */
override def toString = "Now at: " + this.location.name
end Entity
|