Skip to content

Commit

Permalink
add MovingBlock example
Browse files Browse the repository at this point in the history
  • Loading branch information
bjornregnell committed Jun 11, 2024
1 parent 98bbb18 commit b7c3b0c
Showing 1 changed file with 61 additions and 2 deletions.
63 changes: 61 additions & 2 deletions src/main/scala/introprog/examples/TestBlockGame.scala
Original file line number Diff line number Diff line change
@@ -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:
Expand Down Expand Up @@ -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

0 comments on commit b7c3b0c

Please sign in to comment.