Skip to content

Instantly share code, notes, and snippets.

@CodingMinds
Created December 18, 2012 12:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CodingMinds/4327596 to your computer and use it in GitHub Desktop.
Save CodingMinds/4327596 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# A simple demo of a random acting agent which terminates if he found
# food. The amount of attempts will be printed to stdout
# 01.11.12 M. Bittorf <info@coding-minds.com>
# 16.11.12 M. Bittorf <info@coding-minds.com> (updated)
# 18.12.12 M. Bittorf <info@coding-minds.com> (simplified)
import random
import socket
import sys
import re
# config
host = 'localhost'
port = 4567
world = '' #<0.0.0> X Y
# create an INET, STREAMing socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
print >> sys.stderr, "Failed to create socket. Error code: "
+ str(msg[0]) + " , Error message : " + msg[1]
sys.exit()
# resolve
try:
remote_ip = socket.gethostbyname( host )
except socket.gaierror:
print >> sys.stderr, 'Hostname could not be resolved. Exiting'
sys.exit()
# connect and receive greeting
s.connect((host, port))
s.recv(1024)
# try to load a world
try:
s.sendall("world load " + world + "\r\n")
data = s.recv(1024)
if "200" not in data:
print >> sys.stderr, "No world available."
sys.exit()
except socket.error, msg:
print >> sys.stderr, "Failed to communicate with server."
sys.exit()
# go and search food
try:
data = ""
counter = 0
move = -1
while "food" not in data:
while not ":" in data:
s.sendall("environ\r\n")
data = s.recv(1024)
data = ''.join(re.findall('[0-9]+:[\.FO*]+', data))
fitness, sep, env = data.partition(":")
pos = 0
moves = list()
for i in env:
pos += 1
if "." == i or "F" == i:
moves.append(pos)
# debug stuff ..
if len(moves) == 0:
print >> sys.stderr, data
move = moves[random.randint(0,len(moves)-1)]
s.sendall("move " + str(move) + "\r\n")
data = s.recv(1024)
counter+=1
print counter
except socket.error, msg:
print >> sys.stderr, "Failed to communicate with server."
sys.exit()
# close connection
s.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment