Source

snake-challenge / examples / makestory / musashi.rb

#! /usr/bin/ruby
require 'rubygems'
require 'json'
require 'net/http'

@http = Net::HTTP.new("50.56.97.47", 80)
@room_id = ARGV[0] || 0
@user_name = ARGV[1] || 'Musashi'
@direction_hash = {0 => 'left',1 => 'up',2 => 'right',3 => 'down'}

def map
  request = Net::HTTP::Get.new("/room/#{@room_id}/map")
  response = @http.request(request)
  result = JSON.parse(response.body)
  @map = result
end

def info
  request = Net::HTTP::Get.new("/room/#{@room_id}/info")
  response = @http.request(request)
  result = JSON.parse(response.body)
  @info = result
end

def turn
  request = Net::HTTP::Post.new("/room/#{@room_id}/turn")
  request.set_form_data(:id => @me["id"], :round => @info["round"], :direction => @next)
  response = @http.request(request)
  result = JSON.parse(response.body)
  @turn, @info = result[0], result[1]
end

def add
  request = Net::HTTP::Post.new("/room/#{@room_id}/add")
  request.set_form_data(:name => @user_name, :type => "ruby")
  response = @http.request(request)
  result = JSON.parse(response.body)
  @me, @info = result[0], result[1]
end

def think
  @choices = Range.new(0,3).to_a
  @choices -= [((@prev + 2) % 4)]  # avoid turnback
  @next = @choices.shuffle[0]
end

map
add
while @info['status'] == 'waitplayer'
  p 'Waiting Player...' 
  info
  sleep 0.5
end
puts 'Game started'
while @info['status'] == 'running'
  think
  turn
  puts "#{@direction_hash[@next]}"
end

puts "Total Round #{@info['round']}"
puts "Score:"
@info['snakes'].each do |s|
  puts " #{s['name']}[#{s['alive'] ? 'alive' : 'dead'}]: #{s['body'].size} "
end
puts 'Game Over'