Skip to content

Instantly share code, notes, and snippets.

@mslinn
Created October 25, 2011 23:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mslinn/1314819 to your computer and use it in GitHub Desktop.
Save mslinn/1314819 to your computer and use it in GitHub Desktop.
package com.promindis.game.snake.stm
import akka.actor.{ActorRef, Actor}
import java.awt.{Dimension, Graphics2D}
import java.awt.event.{ActionEvent, ActionListener}
import swing._
import swing.Dialog._
import swing.event.Key._
import swing.event.KeyPressed
object Game extends SimpleSwingApplication {
val boardRef = Actor.actorOf(new BoardActor()).start()
val board = new Board(boardRef)
class Board(boardRef:ActorRef) extends Panel {
var doPaint: ((Graphics2D) => Unit) = (onGraphics) => {}
preferredSize = new Dimension(GraphicConverters.converted(World.width), GraphicConverters.converted(World.height))
focusable = true
override def paintComponent(onGraphic: Graphics2D) {
super.paintComponent(onGraphic)
doPaint(onGraphic)
}
def apply(snake: List[ScreenLocation], apple: ScreenLocation) {
def paintPoint(screenLocation: ScreenLocation, color: Color, onGraphics: Graphics2D) {
onGraphics.setColor(color)
onGraphics.fillRect(screenLocation.x, screenLocation.y, screenLocation.width, screenLocation.height)
}
doPaint = (onGraphics: Graphics2D) => {
paintPoint(apple, new Color(210, 50, 90), onGraphics)
snake.foreach {
paintPoint(_, new Color(15, 160, 70), onGraphics)
}
}
repaint()
}
listenTo(keys)
reactions += {
case KeyPressed(source, key, modifiers, location) =>
boardRef ! ReceivedPressed(key)
}
}
def displayMessage(text:String) {
boardRef ! ShowMessage(text)
}
case class ShowMessage(text:String)
case class ReceivedPressed(keyCode:Value)
case class Updated(snake:List[WorldLocation], apple:WorldLocation)
class BoardActor() extends Actor {
import GraphicConverters._
import World._
val directions = Map[Value, WorldLocation](
Left -> Direction.Left,
Right -> Direction.Right,
Up -> Direction.Up,
Down -> Direction.Down
)
protected def receive = {
// update board object in enclosing object with new coordinates via implied apply()
case Updated(snake, apple) =>
board(converted(snake), converted(apple))
case ReceivedPressed(key) =>
Entities.updateSnakeDirection(directions(key))
case ShowMessage(text) =>
showMessage(parent = board, message = text)
}
}
def update(list: List[WorldLocation], location: WorldLocation) {
boardRef ! Updated(list, location)
}
def top = new MainFrame {
title = "Snake"
contents = new FlowPanel() {
val timer = new javax.swing.Timer(100, new ActionListener() {
def actionPerformed(e:ActionEvent) {
Entities.updatePositions()
}
}).start();
contents += board
}
pack()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment