Skip to content

Instantly share code, notes, and snippets.

@ianbishop
Created March 23, 2011 23:13
Show Gist options
  • Select an option

  • Save ianbishop/884237 to your computer and use it in GitHub Desktop.

Select an option

Save ianbishop/884237 to your computer and use it in GitHub Desktop.
More advanced example of Simple Message Passing
class GameState
include Subscriber
def initialize(repeater)
@repeater = repeater
@repeater.subscribe(self)
end
# Handle only messages of attempt move, ignore the rest
def accept(message)
case message[:command]
when "attempt move"
if validateMove(message[:color], message[:x], message[:y])
update_move(message[:color], message[:x], message[:y])
@repeater.broadcast({
command: "accept move",
color: message[:color],
x: message[:x],
y: message[:y]
})
else
@repeater.broadcast({
command: "illegal move",
color: message[:color],
x: message[:x],
y: message[:y]
})
end
else
end
end
# Check if move is in valid range
def validateMove(color, x, y)
if x > 0 && x <= 19 && y > 0 && y <= 19
return true
end
return false
end
# Updates the game state on valid move
def update_move(color, x, y)
puts "#{self.class} State updated: #{color} moved at (#{x},#{y})"
end
end
class GameGUI
include Subscriber
def initialize(repeater)
@repeater = repeater
@repeater.subscribe(self)
end
def accept(message)
case message[:command]
when "accept move"
draw_move(message[:color], message[:x], message[:y])
when "illegal move"
alert_player("Illegal move", message[:color])
else
# do nothing
end
end
# When a player (color) clicks on board location
# x,y we attempt a move by broadcasting it
def on_click(color, x, y)
message = {
command: "attempt move",
color: color,
x: x,
y: y
}
@repeater.broadcast(message)
end
# This is where the real draw code would go!
def draw_move(color, x, y)
puts "#{self.class} drew #{color} at (#{x},#{y})"
end
# Send an alert to the player that their move was illegal
def alert_player(message, color)
puts "#{self.class} ALERT #{color}: #{message}"
end
end
r = Repeater.new
gui = GameGUI.new(r)
state = GameState.new(r)
gui.on_click("black", -1, 23) # illegal move
gui.on_click("black", 3, 8) # legal move
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment