From b7c3b0c0e5a1fcb8b502951aac9f74a08c73895b Mon Sep 17 00:00:00 2001 From: bjornregnell Date: Tue, 11 Jun 2024 20:04:11 +0200 Subject: [PATCH] add MovingBlock example --- .../introprog/examples/TestBlockGame.scala | 63 ++++++++++++++++++- 1 file changed, 61 insertions(+), 2 deletions(-) diff --git a/src/main/scala/introprog/examples/TestBlockGame.scala b/src/main/scala/introprog/examples/TestBlockGame.scala index 018a3c3..8700120 100644 --- a/src/main/scala/introprog/examples/TestBlockGame.scala +++ b/src/main/scala/introprog/examples/TestBlockGame.scala @@ -1,12 +1,17 @@ package introprog.examples -/** Example of a simple BlockGame app with overridden callbacks to handle events +/** Examples of a simple BlockGame app with overridden callbacks to handle events * See the documentation of BlockGame and the source code of TestBlockGame * for inspiration on how to inherit BlockGame to create your own block game. */ object TestBlockGame: /** Create Game and start playing. */ - def main(args: Array[String]): Unit = (new RandomBlocks).play() + def main(args: Array[String]): Unit = + println("Press Enter to toggle random blocks. Close window to continue.") + (new RandomBlocks).play() + println("Opening MovingBlock. Press Ctrl+C to exit.") + (new MovingBlock).start() + println("MovingBlock has ended.") /** A class extending `introprog.BlockGame`, see source code. */ class RandomBlocks extends introprog.BlockGame: @@ -61,3 +66,57 @@ object TestBlockGame: showEnterMessage() gameLoop(stopWhen = state == GameOver) println("Goodbye!") + + end RandomBlocks + + class MovingBlock extends introprog.BlockGame( + title = "MovingBlock", + dim = (10,5), + blockSize = 40, + background = java.awt.Color.BLACK, + framesPerSecond = 50, + messageAreaHeight = 1, + messageAreaBackground = java.awt.Color.DARK_GRAY + ): + + var movesPerSecond: Double = 2 + + def millisBetweenMoves: Int = (1000 / movesPerSecond).round.toInt max 1 + + var _timestampLastMove: Long = System.currentTimeMillis + + def timestampLastMove = _timestampLastMove + + var x = 0 + var y = 0 + + def move(): Unit = + if x == dim._1 - 1 then + x = -1 + y += 1 + end if + x = x+1 + + def erase(): Unit = drawBlock(x, y, java.awt.Color.BLACK) + + def draw(): Unit = drawBlock(x, y, java.awt.Color.CYAN) + + def update(): Unit = + if System.currentTimeMillis > _timestampLastMove + millisBetweenMoves then + move() + _timestampLastMove = System.currentTimeMillis() + + var loopCounter: Int = 0 + + override def gameLoopAction(): Unit = + erase() + update() + draw() + clearMessageArea() + drawTextInMessageArea(s"Loop number: $loopCounter", 1, 0, java.awt.Color.PINK, size = 30) + loopCounter += 1 + + final def start(): Unit = + pixelWindow.show() // möjliggör omstart även om fönstret stängts... + gameLoop(stopWhen = x == dim._1 - 1 && y == dim._2 - 1) + end MovingBlock