Last active
April 15, 2016 17:03
-
-
Save mlankenau/fc538b9b15be64883988d74d44841ba7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'websocket-client-simple' | |
require 'json' | |
class Client | |
LOBBY = "games:lobby" | |
def initialize | |
@mode = :lobby | |
puts "init" | |
@ws = WebSocket::Client::Simple.connect('ws://localhost:4000/socket/websocket') | |
puts "got ws #{@ws}" | |
me = self | |
@ws.on :message do |msg| | |
begin | |
msg = JSON.parse(msg.data) | |
event = msg['event'] | |
payload = msg['payload'] | |
me.send("on_#{event}".to_sym, payload) | |
rescue NoMethodError => e | |
puts "missing method: #{e}" | |
rescue => e | |
puts "#{e.class} #{e.message}, #{e.backtrace[0..100]}" | |
end | |
end | |
@ws.on :open do | |
puts "open event" | |
end | |
@ws.on :close do |e| | |
p e | |
exit 1 | |
end | |
@ws.on :error do |e| | |
p e | |
end | |
end | |
def name | |
"AI Player" | |
end | |
def login | |
puts "login open: #{@connected}" | |
ws_send(LOBBY, 'phx_join', {name: name}) | |
end | |
def ws_send(topic, event, payload) | |
msg = {topic: topic, event: event, payload: payload, ref: next_ref.to_s} | |
puts "sending #{msg}" | |
@ws.send(msg.to_json) | |
end | |
def on_phx_reply(payload) | |
puts "got reply: #{payload}" | |
end | |
def on_challenge(payload) | |
if payload['to'] == name | |
ws_send(LOBBY, 'accept_challenge', from: payload['from'], to: name) | |
end | |
end | |
def on_players_update(payload) | |
puts "got player update #{payload['players']}" | |
end | |
def on_enter_game(payload) | |
if payload['name'] == name | |
@map = payload['map'] | |
puts "enter game: #{payload}" | |
ws_send(LOBBY, 'phx_leave', {}) | |
ws_send("games:#{payload['game_pid']}", 'phx_join', {player_num: payload['player_num']}) | |
@mode = :transient | |
end | |
end | |
def on_update_planets_score(payload) | |
puts "update planets score #{payload}" | |
end | |
def wait_for_challenge | |
@mode = :lobby | |
while @mode == :lobby do | |
sleep 1 | |
ws_send(LOBBY, 'lobby_alive', {from: name}) | |
end | |
end | |
def game_loop | |
@mode = :game | |
while @mode == :game do | |
end | |
end | |
def main_loop | |
loop do | |
if @ws.open? | |
login | |
sleep 1 | |
game_active = true | |
wait_for_challenge | |
game_loop | |
else | |
sleep 1 | |
end | |
end | |
end | |
private | |
def next_ref | |
@next_ref ||= 0 | |
@next_ref += 1 | |
end | |
end | |
client = Client.new | |
client.main_loop |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment