Skip to content

Commit 75f283a

Browse files
committed
add TestBlockGame
1 parent d3686aa commit 75f283a

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package introprog.examples
2+
3+
/** Example of a simple BlockGame app with overridden callbacks to handle events
4+
* See the documentation of BlockGame and the source code of TestBlockGame
5+
* for inspiration on how to inherit BlockGame to create your own block game.
6+
*/
7+
object TestBlockGame {
8+
/** Create Game and start playing. */
9+
def main(args: Array[String]): Unit = (new RandomBlocks).play()
10+
11+
/** A class extending `introprog.BlockGame`, see source code. */
12+
class RandomBlocks extends introprog.BlockGame {
13+
14+
sealed trait State
15+
case object Starting extends State
16+
case object Playing extends State
17+
case object GameOver extends State
18+
19+
var state: State = Starting
20+
var isDrawingRandomBlocks: Boolean = false
21+
22+
def showEnterMessage(): Unit =
23+
drawTextInMessageArea("Press Enter to toggle random blocks.", 0,0)
24+
25+
def showEscapeMessage(): Unit =
26+
drawTextInMessageArea("Press Escape to clear window.", 25, 0)
27+
28+
override def onKeyDown(key: String): Unit = {
29+
print(s" Key down: $key")
30+
key match {
31+
case "Escape" =>
32+
clearWindow()
33+
drawCenteredText("ESCAPED TO BLACK SPACE!")
34+
showEnterMessage()
35+
case "Enter" =>
36+
isDrawingRandomBlocks = !isDrawingRandomBlocks
37+
showEscapeMessage()
38+
case _ =>
39+
}
40+
}
41+
42+
override def onKeyUp(key: String): Unit = print(s" Key up: $key")
43+
44+
override def onMouseDown(pos: (Int, Int)): Unit = print(s" Mouse down: $pos")
45+
46+
override def onMouseUp(pos: (Int, Int)): Unit = print(s" Mouse up: $pos")
47+
48+
override def onClose(): Unit = {
49+
print(" Window Closed.")
50+
state = GameOver
51+
}
52+
override def gameLoopAction(): Unit = {
53+
import scala.util.Random.nextInt
54+
def rndPos: (Int, Int) = (nextInt(dim._1), nextInt(dim._2))
55+
def rndColor = new java.awt.Color(nextInt(256), nextInt(256), nextInt(256))
56+
print(".")
57+
if (isDrawingRandomBlocks) {
58+
drawBlock(rndPos._1, rndPos._2, rndColor)
59+
}
60+
}
61+
62+
def play(): Unit = {
63+
state = Playing
64+
println(s"framesPerSecond == $framesPerSecond")
65+
showEnterMessage()
66+
gameLoop(stopWhen = state == GameOver)
67+
println("Goodbye!")
68+
}
69+
}
70+
}

0 commit comments

Comments
 (0)