| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149 |
- require 'socket'
- require 'yaml/store'
- config = YAML::Store.new "config.store"
- config.transaction do
- $name = config["name"]
- $password = config["password"]
- $host = config["host"]
- $port = config["port"]
- end
- def connect(host, port)
- $sock = TCPSocket.new(host, port)
- # join($name,$password)
- while line = $sock.gets
- puts line
- parse(line)
- end
- end
- def join(name, password)
- send("join", name, password)
- end
- def parse(message)
- parts = message.split('|')
- case parts[0].strip
- when "error"
- puts "error occured " + parts[1]
- when "game"
- $gameW = parts[1].to_i
- $gameH = parts[2].to_i
- $id = parts[3].to_i
- initmap()
- when "pos"
- $map[parts[2].to_i][parts[3].to_i] = parts[1].to_i
- # puts $map
- if parts[1].to_i === $id
- # store our position
- $myX = parts[2].to_i
- $myY = parts[3].to_i
- end
- when "tick"
- decide()
- when "die"
- parts.drop(1).each { |player| cleanup(player) }
- when "message"
- when "win", "lose"
- reset()
- when "motd"
- join($name, $password)
- end
- end
- def cleanup(player)
- id = player.to_i
- puts "Removing tiles from player ##{id}"
- $dead.append(id)
- # $map.each { |row| row.each { |element| if element == id then element = -1 end}}
- end
- $tries = 0
- def check_front
- # puts "#{$direction} at #{$myX},#{$myY} - try: #{$tries}"
- case $direction
- when "up"
- value = $map[overflow($myX, $gameW)][overflow($myY - 1, $gameH)]
- when "down"
- value = $map[overflow($myX, $gameW)][overflow($myY + 1, $gameH)]
- when "left"
- value = $map[overflow($myX - 1, $gameW)][overflow($myY, $gameH)]
- when "right"
- value = $map[overflow($myX + 1, $gameW)][overflow($myY, $gameH)]
- end
- $tries = $tries + 1
- puts "check_front: #{value}"
- return value
- end
- def overflow(new, max)
- if new >= max
- return 0
- end
- if new < 0
- return max - 1
- end
- new
- end
- def new_direction
- case $direction
- when "up"
- "right"
- when "down"
- "left"
- when "left"
- "up"
- when "right"
- "down"
- end
- end
- def decide()
- $tries = 0
- while check_front > -1 && !$dead.include?(check_front)
- $direction = new_direction()
- if $tries > 4
- break
- end
- end
- send("move", $direction)
- end
- def chat(message)
- send("chat", message)
- end
- def reset() end
- def send(msg, *param)
- if param.length > 0
- snd = "#{msg}|#{param.join("|")}"
- else
- snd = msg
- end
- $sock.puts(snd)
- puts(snd)
- end
- def initmap()
- $map = Array.new($gameH) { Array.new($gameW) { -1 } }
- $direction = "up"
- $dead = Array.new(0)
- chat("Rock and Stone!")
- end
- connect($host, $port)
|