Skip to content

Commit b7c3b0c

Browse files
committed
add MovingBlock example
1 parent 98bbb18 commit b7c3b0c

File tree

1 file changed

+61
-2
lines changed

1 file changed

+61
-2
lines changed

src/main/scala/introprog/examples/TestBlockGame.scala

Lines changed: 61 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,17 @@
11
package introprog.examples
22

3-
/** Example of a simple BlockGame app with overridden callbacks to handle events
3+
/** Examples of a simple BlockGame app with overridden callbacks to handle events
44
* See the documentation of BlockGame and the source code of TestBlockGame
55
* for inspiration on how to inherit BlockGame to create your own block game.
66
*/
77
object TestBlockGame:
88
/** Create Game and start playing. */
9-
def main(args: Array[String]): Unit = (new RandomBlocks).play()
9+
def main(args: Array[String]): Unit =
10+
println("Press Enter to toggle random blocks. Close window to continue.")
11+
(new RandomBlocks).play()
12+
println("Opening MovingBlock. Press Ctrl+C to exit.")
13+
(new MovingBlock).start()
14+
println("MovingBlock has ended.")
1015

1116
/** A class extending `introprog.BlockGame`, see source code. */
1217
class RandomBlocks extends introprog.BlockGame:
@@ -61,3 +66,57 @@ object TestBlockGame:
6166
showEnterMessage()
6267
gameLoop(stopWhen = state == GameOver)
6368
println("Goodbye!")
69+
70+
end RandomBlocks
71+
72+
class MovingBlock extends introprog.BlockGame(
73+
title = "MovingBlock",
74+
dim = (10,5),
75+
blockSize = 40,
76+
background = java.awt.Color.BLACK,
77+
framesPerSecond = 50,
78+
messageAreaHeight = 1,
79+
messageAreaBackground = java.awt.Color.DARK_GRAY
80+
):
81+
82+
var movesPerSecond: Double = 2
83+
84+
def millisBetweenMoves: Int = (1000 / movesPerSecond).round.toInt max 1
85+
86+
var _timestampLastMove: Long = System.currentTimeMillis
87+
88+
def timestampLastMove = _timestampLastMove
89+
90+
var x = 0
91+
var y = 0
92+
93+
def move(): Unit =
94+
if x == dim._1 - 1 then
95+
x = -1
96+
y += 1
97+
end if
98+
x = x+1
99+
100+
def erase(): Unit = drawBlock(x, y, java.awt.Color.BLACK)
101+
102+
def draw(): Unit = drawBlock(x, y, java.awt.Color.CYAN)
103+
104+
def update(): Unit =
105+
if System.currentTimeMillis > _timestampLastMove + millisBetweenMoves then
106+
move()
107+
_timestampLastMove = System.currentTimeMillis()
108+
109+
var loopCounter: Int = 0
110+
111+
override def gameLoopAction(): Unit =
112+
erase()
113+
update()
114+
draw()
115+
clearMessageArea()
116+
drawTextInMessageArea(s"Loop number: $loopCounter", 1, 0, java.awt.Color.PINK, size = 30)
117+
loopCounter += 1
118+
119+
final def start(): Unit =
120+
pixelWindow.show() // möjliggör omstart även om fönstret stängts...
121+
gameLoop(stopWhen = x == dim._1 - 1 && y == dim._2 - 1)
122+
end MovingBlock

0 commit comments

Comments
 (0)