1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
#!/usr/bin/env python

import numpy as n
import random as r
import cairo as c
import subprocess as s

class Hamster:
    """This is my hamster class controlling the movement of the hamster.
On his way across the board the hamster has to avoid obstacles and can
find some seeds, which he can eat.

Among methods for achieving this mission the class needs a bit more
management tools."""

    blocked_moves = 0
    board = None
    dead = False
    name = "John Doe"
    ORIENTATIONS = [
        n.array((1,0)),
        n.array((0,-1)),
        n.array((-1,0)),
        n.array((0,1))
    ]
    orientation = None
    position = n.array((0,0))
    seeds = 0
    turn_direction = None
    verbose = False

    def __init__(self,**kwargs):
        "The hamster is placed on a tile of a board looking in a direction."
        
        if kwargs.has_key("position"):
            self.set_position(kwargs["position"])
        if kwargs.has_key("orientation"):
            self.set_orientation(kwargs["orientation"])
        else:
            self.set_orientation(self.ORIENTATIONS[r.randint(0,3)])
        if not kwargs.has_key("board"):
            raise AttributeError, "A Schachbrett instance is needed!"
        else:
            self.set_board(kwargs["board"])
        if kwargs.has_key("name"):
            self.set_name(kwargs["name"])
        if kwargs.has_key("verbose"):
            self.set_verbose(kwargs["verbose"])

    def feed(self):
        "If the hamster finds a seed, he will eat it."
        
        if not self.is_alive(): return
        if self.board.contains_seed(self.get_position()):
            self.seeds += 1
            self.board.remove_seed(self.get_position())

    def get_position(self):
        return self.position

    def get_orientation(self):
        return self.orientation

    def is_alive(self):
        return not self.dead

    def is_verbose(self):
        return self.verbose

    def move(self):
        """Moving looks a bit more difficult. Before the hamster actually
can move we have to check whether his destination in not block by an
obstacle or another hamster. If so, he has to move to another direction."""

        if not self.is_alive():
            return
        
        new_position = self.get_position() + self.get_orientation()
        if self.board.is_available(new_position):
            self.talk("%s hat freie Fahrt\n%s -> %s" % (self.name,str(self.get_position()),str(new_position)))
            self.set_position(new_position)
            self.blocked_moves = 0
            self.turn_direction = None
        else:
            self.talk("%s %s ist blockiert in Richtung %s" % (self.name,self.get_position(),self.get_orientation()))
            self.blocked_moves += 1
            if self.blocked_moves > 4:
                self.talk("%s ist tot" % self.name)
                self.set_dead()
                return
            if self.turn_direction == None:
                self.turn_direction = r.random()
            if self.turn_direction < .5:
                self.rotate_right()
            else:
                self.rotate_left()

    def set_board(self,board):
        "Placing the hamster on a board."
        
        if str(board.__class__).split('.')[-1] == 'Schachbrett':
            self.board = board
        else:
            raise TypeError, 'Argument board requires a Schachbrett instance!'

    def set_dead(self):
        self.dead = True

    def set_name(self,name):
        if not self.is_alive():
            return
        if type(name) == type(self.name):
            if len(name) > 3:
                self.name = name
            else:
                raise ValueError, 'Please choose a name of length > 3!'
        else:
            raise TypeError, 'The name of the hamster should be a string!'

    def set_position(self,xy):
        if not self.is_alive():
            return
        if type(xy) == type(self.position):
            if len(xy) == len(self.position):
                self.position = xy
            else:
                raise ValueError, 'New position is not in 2D'
        else:
            raise TypeError, 'New position is no numpy array'

    def set_orientation(self,xy):
        if not self.is_alive():
            return
        if type(xy) == type(n.array((1,1))):
            if len(xy) == 2:
                self.orientation = xy
            else:
                raise ValueError, 'This is no valid 2D direction:' + str(xy)
        else:
            raise ValueError, 'This is no valid direction:' + str(xy)

    def set_verbose(self,bool):
        if bool == True or bool == False:
            self.verbose = bool

    def rotate_left(self):
        if not self.is_alive:
            return
        self.set_orientation(self.get_orientation()[::-1] * n.array((-1,1)))

    def rotate_right(self):
        if not self.is_alive():
            return
        self.set_orientation(self.get_orientation()[::-1] * n.array((1,-1)))

    def talk(self,text):
        if self.is_verbose():
            print text

class Schachbrett:
    """This is my board on which the hamster can walk around.
    
Additionally I added some fancy rendering..."""
    
    size = n.array((8,8))
    blocked = [n.array((0,5)),n.array((6,2))]
    seeds = [n.array((1,1)),n.array((3,3)),n.array((0,0))]

    def __init__(self,**kwargs):
        pass

    def contains_seed(self,xy):
        "Testing whether the field contains a seed."
        
        if not type(xy) == type(n.array((1,1))):
            raise TypeError, 'Queried position is no numpy array'
        else:
            if not len(xy) == 2:
                raise ValueError, 'Queried position is not in 2D'
                
        for seed in self.seeds:
            if (seed == xy).all():
                return True
            else:
                return False

    def is_available(self,xy):
        "Testing whether the field is available"
        
        if self.is_blocked(xy) or self.is_occupied(xy) or not self.is_on_board(xy):
            return False
        else:
            return True

    def is_blocked(self,xy):
        "Tests whether the field is blocked by an obstacle."
        
        if not type(xy) == type(n.array((1,1))):
            raise TypeError, 'Queried position is no numpy array'
        else:
            if not len(xy) == 2:
                raise ValueError, 'Queried position is not in 2D'

        for b in self.blocked:
            if (xy == b).all():
                return True
        else:
            return False

    def is_occupied(self,xy):
        "Tests, whether a field is occupied by another hamser."
        
        if not type(xy) == type(n.array((1,1))):
            raise TypeError, 'Queried position is no numpy array'
        else:
            if not len(xy) == 2:
                raise ValueError, 'Queried position is not in 2D'

        for h in Kontrol.HAMSTERS:
            if (xy == h.get_position()).all():
                return h
        else:
            return False

    def is_on_board(self,xy):
        "The board has no infinite size. We have to prevent the hamster from running away."
        
        if (xy[0] > -1 and xy[0] < self.size[0]) and (xy[1] > -1 and xy[1] < self.size[1]):
            return True
        else:
            return False

    def draw_ascii(self):
        "This is the basic output of the situation on the board in the shell"
        
        board = [['_' for j in range(self.size[0])] for i in range(self.size[1])]
        for h in Kontrol.HAMSTERS:
            x,y = h.get_position()
            board[x][y] = 'H'
        for line in board:
            print ''.join(line)

    def draw_blocked(self):
        "This is the fancy output drawing a blocked field"
        
        self.ctx.set_source_rgb(.8,0,0)
        self.ctx.arc(.5*self.length,.5*self.length,.4*self.length,0,360)
        self.ctx.fill_preserve()
        self.ctx.set_source_rgb(0,0,0)
        self.ctx.stroke()
        self.ctx.set_source_rgb(1,1,1)
        self.ctx.rectangle(.25*self.length,.45*self.length,.5*self.length,.1*self.length)
        self.ctx.fill()

    def draw_board(self,tick=0):
        "This is the fancy output. At first we have to draw an empty board."
        
        self.length = 50
        self.width, self.height = (self.size[0]+1)*self.length, (self.size[1]+1)*self.length
        self.surface = c.ImageSurface(c.FORMAT_ARGB32, self.width, self.height)
        self.ctx = c.Context(self.surface)
        self.ctx.set_source_rgb(1,1,1)
        self.ctx.rectangle(0, 0, self.width, self.height)
        self.ctx.fill()
        self.ctx.translate(.5*self.length,.5*self.length)
        for i in range(self.size[0]):
            for j in range(self.size[1]):
                self.draw_field(i,j)

        self.surface.write_to_png('hamster_%05i.png' % tick)

    def draw_field(self,x,y):
        """This part of the fancy output draws a field and calls another 
method depending on the status of the tile."""
        
        self.ctx.save()
        self.ctx.translate(x*self.length,y*self.length)
        self.ctx.set_source_rgb(.2,.2,.2)
        #self.ctx.rectangle(-.5*self.length,-.5*self.length,.5*self.length,.5*self.length)
        self.ctx.rectangle(0,0,self.length,self.length)
        self.ctx.stroke()
        if self.contains_seed(n.array((x,y))):
            self.draw_seed()
        if self.is_blocked(n.array((x,y))):
            self.draw_blocked()
        h = self.is_occupied(n.array((x,y)))
        if h:
            self.draw_hamster(h)
        self.ctx.restore()

    def draw_hamster(self,h):
        "This method draws the hamster in the fancy output"
        
        self.ctx.arc(.5*self.length,.5*self.length,.3*self.length,0,360)
        if h.is_alive():
            self.ctx.set_source_rgb(1,.5,0)
        else:
            self.ctx.set_source_rgb(.3,.3,.3)
        self.ctx.fill_preserve()
        self.ctx.set_source_rgb(0,0,0)
        self.ctx.stroke()

        d = h.get_orientation()
        x = [.5*self.length,.5*self.length]
        x = x+d*.3*self.length
        self.ctx.arc(x[0],x[1],.1*self.length,0,360)
        #self.ctx.rectangle(x[0],y[0],x[0],y[0])
        self.ctx.fill()

    def draw_seed(self):
        "Fancy output: Draws the seed"
        
        self.ctx.arc(.2*self.length,.2*self.length,.1*self.length,0,360)
        self.ctx.set_source_rgb(1,1,0)
        self.ctx.fill_preserve()
        self.ctx.set_source_rgb(0,0,0)
        self.ctx.stroke()

    def gen_blocks(self,i=5):
        "Convenience method: Generates series of blocked tiles."
        
        for i in range(i):
            self.blocked.append(n.array((r.randint(0,8),r.randint(0,8))))

    def remove_seed(self,xy):
        "Removes seed from board after it has been eaten."
        
        if self.contains_seed(xy):
            for i in range(len(self.seeds)):
                if (xy == self.seeds[i]).all():
                    self.seeds.pop(i)
                    break
        else:
            raise ValueError, 'At this coordinate is no seed.'

class Kontrol:
    """This is the important class of this script. It coordinates
the movement of the hamster. It controls in which order the hamsters
are moving.

If we expanded this class, we could manage multiple hamsters on multiple
boards! If we wanted a Monte Carlo-style movement, we would write 
another tick method."""
    
    HAMSTERS = []
    ticks = 0

    def __init__(self):
        "Instantiates the board and blocked tiles."
        
        self.board = Schachbrett()
        self.board.gen_blocks(15)

    def add_hamster(self,hamster):
        "Adds a hamster to a board."
        
        if str(hamster.__class__).split('.')[-1] == 'Hamster':
            Kontrol.HAMSTERS.append(hamster)
        else:
            raise TypeError, 'A Hamster instance is requireds!'

    def run(self,limit=10):
        "In analogy this method is called run. This method actually does something."
        
        for i in range(limit):
            self.tick()

    def tick(self,draw=True):
        "This method draws the board and moves the hamsters."
        
        if draw:
            self.board.draw_board(self.ticks)
        for h in Kontrol.HAMSTERS:
            h.move()
            h.feed()
        
        self.ticks += 1

if __name__ == '__main__':
    K = Kontrol()
    K.add_hamster(Hamster(board=K.board,orientation=Hamster.ORIENTATIONS[1],position=n.array((4,4)),verbose=False))
    K.add_hamster(Hamster(board=K.board,orientation=Hamster.ORIENTATIONS[3],position=n.array((0,2)),verbose=False))
    K.add_hamster(Hamster(board=K.board,orientation=Hamster.ORIENTATIONS[2],position=n.array((3,1)),verbose=False))
    K.add_hamster(Hamster(board=K.board,orientation=Hamster.ORIENTATIONS[0],position=n.array((1,1)),verbose=False))
    K.run(120)

    cmd = ['mencoder', 'mf://*.png', '-mf', 'w=450:h=450:fps=5:type=png', '-ovc', 'lavc', '-lavcopts', 'vcodec=mpeg4:mbd=2:trell', '-oac', 'copy', '-o', 'hamster.avi']
    result = s.Popen(cmd)
    print "Images rendered"
    s.Popen(['rm','hamster_*.png'])
    print "Done"