Created
December 18, 2012 12:34
-
-
Save CodingMinds/4327596 to your computer and use it in GitHub Desktop.
a simplified version of https://github.com/CodingMinds/world_simulator/blob/master/demos/random_agent.py
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
#!/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 <[email protected]> | |
# 16.11.12 M. Bittorf <[email protected]> (updated) | |
# 18.12.12 M. Bittorf <[email protected]> (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