HTMLify

rbott.py
Views: 163 | Author: abh
from random import randint
from time import sleep

class Grid:
    def __init__(self, bots = [].copy()):
        self.width = 5
        self.height = 5
        self.bots = bots

    def __str__(self):
        s = [(["."]*self.width).copy()for _ in range(self.height)]
        for bot in self.bots:
            s[bot.position[0]][bot.position[1]] = bot.symbol
        #s = "\n".join(c for c in line for line in s)
        g = ""
        for line in s:
            g += "".join(line) + "\n"
        return g

    def add_bot(self, bot):
        self.bots.append(bot)


class Bot:
    def __init__(self, grid, symbol="@"):
        self.position = [0, 0]
        self.grid = grid
        self.symbol = symbol
        self.age = 0

    def walk(self):
        self.position[0] += [1, 0, -1][randint(0, 2)]
        self.position[1] += [1, 0, -1][randint(0, 2)]
        while self.position[0] < 0:
            self.position[0]+=1
        while self.position[0] >= self.grid.width:
            self.position[0]-=1
        while self.position[1] < 0:
            self.position[1]+=1
        while self.position[1] >= self.grid.height:
            self.position[1]-=1
        self.age += 1

grid = Grid()
grid.width = 10
grid.height = 10
a = Bot(grid, "A")
b = Bot(grid, "B")
b.position = [9, 9]

bots = [a, b]
symbols = "QWERTYUIOPASDFGHJKLMNBVCXZ"
grid.add_bot(a)
grid.add_bot(b)

for _ in range(600):
    #print(list(map(lambda bot:bot.age, grid.bots)))
    for bot in grid.bots:
        bot.walk()
        for b in grid.bots:
            if bot is b:
                continue
            if bot.position == b.position and (bot.age >= b.age >= 18):
                grid.add_bot((Bot(grid, symbols[randint(0, 25)])))
                grid.bots[-1].position = bot.position.copy()
                #while grid.bots[-1].position in map(lambda bot:bot.position, grid.bots[:-1]):
                #    grid.bots[-1].walk()
                bot.walk()
                b.walk()
                grid.bots[-1].walk()
    print(grid)
    sleep(0.1)

Comments