Beispiel #1
0
class Chase:
    def __init__(self, init_pos_limit, sheep_move_dist, wolf_move_dist):
        self.alive_sheep = 0
        self.wolf_move_dist = wolf_move_dist
        self.sheep_move_dist = sheep_move_dist
        self.init_pos_limit = init_pos_limit
        self.num_of_sheep = 0
        self.sheep_arr = []
        self.wolf = Wolf(self.wolf_move_dist)
        self.current_turn = 0

    def reset(self):
        self.current_turn = 0
        self.wolf.reset()
        self.num_of_sheep = 0
        self.sheep_arr = []
        self.alive_sheep = 0

    def add_sheep(self, x, y):
        sheep = Sheep(self.init_pos_limit, self.sheep_move_dist, x, y)
        self.sheep_arr.append(sheep)
        self.alive_sheep += 1

    def step(self):
        self.alive_sheep = 0
        self.current_turn += 1
        for s in self.sheep_arr:
            if s not in self.wolf.eaten and s is not None:  # jesli nie zjedzona
                s.move()  # rusz owce
                self.alive_sheep += 1  # inkrementuj licznik zywych owiec
        if self.wolf.search(self.sheep_arr):
            self.alive_sheep -= 1
Beispiel #2
0
def main():
    pygame.init()
    random.seed(None)
    font = pygame.freetype.Font(None, 20)
    screen = pygame.display.set_mode(RESOLUTION)
    pygame.display.set_caption("Nu Pogodi!")
    bg = image.load("images/BackgroundScreen.png")
    chikens = image.load("images/chickens.png")
    wolf = Wolf(PLAYER_POSITION)
    bodyIsLeft = True
    armsIsUp = True
    eggs = []
    time = 0
    timer = pygame.time.Clock()
    running = True
    score = 0
    while 1:
        for e in pygame.event.get():
            if e.type == QUIT:
                raise SystemExit("QUIT")
            if e.type == KEYDOWN and e.key == K_LEFT:
                bodyIsLeft = True
            if e.type == KEYDOWN and e.key == K_RIGHT:
                bodyIsLeft = False
            if e.type == KEYDOWN and e.key == K_UP:
                armsIsUp = True
            if e.type == KEYDOWN and e.key == K_DOWN:
                armsIsUp = False

        screen.blit(bg, (0, 0))
        screen.blit(chikens, (0, 0))
        wolf.draw(screen, bodyIsLeft, armsIsUp)
        if running:
            time += timer.get_time()
        if time > TIME_PER_STEP:
            time = 0
            shift = False
            for egg in eggs:
                should_catch = egg.update()
                if should_catch:
                    if catch_egg(egg, bodyIsLeft, armsIsUp):
                        score = score + 1
                        shift = True
                    else:
                        running = False
            if shift:
                eggs.pop(0)
            eggs.append(Egg())

        for egg in eggs:
            egg.draw(screen)

        scoreText, _ = font.render("{}".format(score), Color("#ff0000"))
        if not running:
            scoreText, _ = font.render("Game Over {}".format(score),
                                       Color("#ff0000"))
        screen.blit(scoreText, (100, 20))
        pygame.display.update()
        if running:
            timer.tick(60)
Beispiel #3
0
 def __init__(self, init_pos_limit, sheep_move_dist, wolf_move_dist):
     self.alive_sheep = 0
     self.wolf_move_dist = wolf_move_dist
     self.sheep_move_dist = sheep_move_dist
     self.init_pos_limit = init_pos_limit
     self.num_of_sheep = 0
     self.sheep_arr = []
     self.wolf = Wolf(self.wolf_move_dist)
     self.current_turn = 0
Beispiel #4
0
def import_from_json(f, meadow, scale, sheep_list_sheeps, points_list):
    meadow.delete("all")
    sheep_list_sheeps.clear()
    points_list.clear()
    scale.set(0)

    # zapis danych z pliku do zmiennej
    with open(f) as json_file:
        data = json.load(json_file)

        # zapis poszczegolnych fragmentow do zmiennych
        bg_color = data['bg_color']
        wolf_color = data['wolf_color']
        wolf_pos = data['wolf_pos']
        sheep_color = data['sheep_color']
        sheep_pos = data['sheep_pos']

        # podzial zmiennej wolf_pos na liste z wspolrzednymi wilka
        wolf_after = wolf_pos.split(',')
        wolf_x = wolf_after[0]
        wolf_y = wolf_after[1]

        # przypisanie wszystkich atrybutow do wilka
        wolf = Wolf()
        wolf.x = float(wolf_x)
        wolf.y = float(wolf_y)
        wolf.wolf_color = wolf_color
        drawn_wolf = draw_wolf(meadow, wolf.x, wolf.y, wolf.wolf_color, scale)

        # ilosc owiec zapisanych w pliku
        length = len(sheep_pos)

        # stworzenie listy owiec, do ktorej zapisze sie dane z pliku
        sheep_list_sheeps = SheepList()

        for i in range(0, length):
            # dzielimy kazdy element listy na mniejsza tablice, ktorej pierwszy element to x, a drugi to y
            pom = sheep_pos[i].split(',')
            # konwertujemy elementy tablicy na float
            x = float(pom[0])
            y = float(pom[1])
            # dodajemy owce o wspolrzednych z pliku do stworzonej listy
            sheep_list_sheeps.sheep_add(Sheep(i, x, y))
            # rysujemy te owce na lace
            point = draw_sheep(meadow, x, y, sheep_color, scale)
            # dodajemy narysowane punkty do listy
            sheep_list_sheeps.point_add(point)

        # każdej owcy z listy ustawiamy kolor wczytany z pliku
        for sheep in sheep_list_sheeps.sheep_list:
            sheep.sheep_color = sheep_color

        # zwracamy te elementy, ktore sa istotne przy kolejnych krokach symulacji
        return sheep_color, wolf, drawn_wolf, bg_color
 def __init__(self, init_pos_limit, sheep_move_dist, wolf_move_dist,
              sheep_number, turns_number, wait):
     log = "Info level: Setting simulation details " + str(init_pos_limit) + " " + str(sheep_move_dist) + " " + \
           str(wolf_move_dist) + " " + str(sheep_move_dist) + " " + str(sheep_number) + " " + str(turns_number) + " "
     logging.info(log)
     self.turns_number = turns_number
     self.wolf = Wolf(wolf_move_dist)
     self.wait_character = wait
     self.sheep_number = sheep_number
     self.alive_sheep_number = sheep_number
     for _ in range(sheep_number):
         self.sheep_list.append(Sheep(init_pos_limit, sheep_move_dist))
	def __init__(self, srn_sz: (float, float), clock: pygame.time.Clock, screen: pygame.Surface):
		"""
		Initializes the World

		Args:
			srn_sz ( (float, float) ): Screen size
			clock (pygame.time.Clock): pygame Clock
			screen (pygame.Surface): pygame Screen
		"""

		self.running = True

		self._clock = clock
		self.screen = screen
		
		self.runtime = 0
		self.runtime_checkpoint = 0

		self.size = srn_sz
		self.rabbits = []
		self.wolves = []
		self.food = []

		for _ in range(20):
			self.rabbits.append(Rabbit(self, self._random_pos(), 2.5))

		for _ in range(6):
			self.wolves.append(Wolf(self, self._random_pos(), 3.0))

		for _ in range(80):
			self.food.append(Food(self, self._random_pos()))

		self._update_screen()
Beispiel #7
0
  def on_init(self):
    pygame.init()
    self.screen = pygame.display.set_mode(
      self.size, pygame.HWSURFACE | pygame.DOUBLEBUF)

    # Fill background and blits everything to the screen
    self.background = pygame.Surface(self.size)
    self.background = self.background.convert()
    self.background.fill(BG_COLOR)
    self.screen.blit(self.background, (0, 0))
    pygame.display.flip()

    self.terrain = Terrain()

    self.beaver = Beaver()
    self.beaversprite = pygame.sprite.RenderPlain(self.beaver)
    self.generationtime = pygame.time.get_ticks()

    self.brain = Brain()
    self.brain.environment.setbeaver(self.beaver)

    self.wolf = Wolf()
    self.wolfsprite = pygame.sprite.RenderPlain(self.wolf)

    self._clock = pygame.time.Clock()
    self._running = True
Beispiel #8
0
 def mate(self):
     if len(self.wolves) >= 2:
         if self.average_genetic_variance() > 1.5:
             num_pups = floor(normalvariate(7.45, 2))
         else:
             num_pups = floor(normalvariate(3.40, 2))
         self.wolves.extend(
             Wolf(self.determine_pup_alleles()) for i in range(0, num_pups))
Beispiel #9
0
    def small_setup(self):

        self.controller.put(Wolf(20, 20))
        self.controller.put(Bunny(19, 20))
        self.controller.put(Bunny(22, 20))
        self.controller.put(Bunny(21, 19))
        self.controller.put(Bunny(21, 23))
        self.controller.put(Bunny(21, 22))
Beispiel #10
0
 def __init__(self):
     super(Gameplay, self).__init__()
     w, h = SCREEN_RECT.size
     self.all_sprites = pg.sprite.LayeredUpdates()
     self.background = make_background((w, h))
     self.player = Player(SCREEN_RECT.center, self.all_sprites)
     self.wolves = pg.sprite.Group()
     for _ in range(10):
         pos = randint(32, w - 32), randint(32, h - 32)
         Wolf(pos, self.wolves, self.all_sprites)
     self.trees = pg.sprite.Group()
     for _ in range(25):
         pos = randint(0, w), randint(0, h)
         Tree(pos, self.trees, self.all_sprites)
Beispiel #11
0
    def random_setup(self):
        for x in range(self.game_size):
            for y in range(self.game_size):

                num = random()
                if num < 0.01:  # 1% bunnies
                    thing = Bunny(x, y)
                    self.controller.put(thing)
                elif num < 0.013:  # 0.3% wolves
                    thing = Wolf(x, y)
                    self.controller.put(thing)
                elif num < 0.315:  # 30% bushes
                    thing = Bush(x, y)
                    self.controller.put(thing)
                else:  # 60% empty space
                    pass  # and 100% reason to remember the name <---- joke comment, disregard
def run():
    pygame.init()

    size = [700,700]
    screen = pygame.display.set_mode(size)

    simple = pygame.image.load('l_one.png')
    simple_rect = simple.get_rect()

    #create fox and wolf
    fox_avatar = Fox(screen)
    wolf_avatar = Wolf(screen)
    #speed
    clock = pygame.time.Clock()
    #world shift
    world_shift_hor = 0
    world_shift_vert = 0

    pygame.display.set_caption("Fox Dash:Avoid the Wolf for 30 seconds ")
    
    #start and create timer
    startTime = pygame.time.get_ticks()
    seconds = 0

    game_cont = True
    while game_cont == True:
        #show on screen
        screen.blit(simple, simple_rect)
        fox_avatar.blitme()
        wolf_avatar.blitme()
        #check movments
        events(fox_avatar)
        fox_avatar.update(screen)
        wolf_avatar.update(screen,fox_avatar)
        pygame.display.update()
        #collision detection
        if check(fox_avatar, wolf_avatar):
            print('Game over')
            game_cont = False
        #timer 30 seconds
        #restart timer
        if seconds >= 30:
            #startTime = pygame.time.get_ticks()
            #seconds = 0
            print("Round done, You are safe!")
            game_cont = False
        seconds=(pygame.time.get_ticks()-startTime)/1000
        #check to see if there is a collision
        ans = check(fox_avatar, wolf_avatar)
        #speed
        clock.tick(30)
        pygame.display.flip()
Beispiel #13
0
    def __init__(self):
        super(Gameplay, self).__init__()
        w, h = SCREEN_RECT.size
        self.all_sprites = pg.sprite.LayeredUpdates()
        self.background = make_background((w, h))
        self.fog = pg.Surface((w, h), pg.SRCALPHA)
        self.fog.fill((0, 0, 0, 255))
        self.player = Player(SCREEN_RECT.center, self.all_sprites)
        self.wolves = pg.sprite.Group()
        for _ in range(10):
            pos = randint(32, w - 32), randint(32, h - 32)
            Wolf(pos, self.wolves, self.all_sprites)
        self.trees = pg.sprite.Group()
        for _ in range(25):
            pos = randint(0, w), randint(0, h)
            Tree(pos, self.trees, self.all_sprites)

        self.tree_shadows = []
        for tree in self.trees:
            self.tree_shadows.append(Shadow(tree.footprint))
Beispiel #14
0
    def __init__(self):

        totalarea = c.MAPSIZE[0] * c.MAPSIZE[1]
        self.map = []
        self.wolves = {}
        self.deer = {}

        for x in range(c.MAPSIZE[0]):
            self.map.append([])
            for y in range(c.MAPSIZE[1]):
                self.map[x].append(Tile([x, y]))

                if np.random.random() < (c.INITDEER / totalarea):
                    self.map[x][y].id = "deer"
                    self.map[x][y].addAnimal(Deer())
                    self.deer[(x, y)] = self.map[x][y].animal

        while len(self.wolves) < c.INITWOLVES:
            x = np.random.randint(c.MAPSIZE[0] / 2 - 5, c.MAPSIZE[0] / 2 + 5)
            y = np.random.randint(c.MAPSIZE[1] / 2 - 5, c.MAPSIZE[1] / 2 + 5)
            if self.map[x][y].id == "empty":
                self.map[x][y].id = "wolf"
                self.map[x][y].addAnimal(Wolf())
                self.wolves[(x, y)] = self.map[x][y].animal
Beispiel #15
0
class Game:
  def __init__(self):
    self._running = True
    self.screen = None
    self.size = self.width, self.height = SCREEN_WIDTH, SCREEN_HEIGHT

  def on_init(self):
    pygame.init()
    self.screen = pygame.display.set_mode(
      self.size, pygame.HWSURFACE | pygame.DOUBLEBUF)

    # Fill background and blits everything to the screen
    self.background = pygame.Surface(self.size)
    self.background = self.background.convert()
    self.background.fill(BG_COLOR)
    self.screen.blit(self.background, (0, 0))
    pygame.display.flip()

    self.terrain = Terrain()

    self.beaver = Beaver()
    self.beaversprite = pygame.sprite.RenderPlain(self.beaver)
    self.generationtime = pygame.time.get_ticks()

    self.brain = Brain()
    self.brain.environment.setbeaver(self.beaver)

    self.wolf = Wolf()
    self.wolfsprite = pygame.sprite.RenderPlain(self.wolf)

    self._clock = pygame.time.Clock()
    self._running = True

  def on_event(self, event):
    if event.type == pygame.QUIT:
      self._running = False

  def on_loop(self):
    self.beaver.seteyeview(self.terrain.terraingroup)
    self.beaversprite.update()

    self.brain.experiment.doInteractions(1)

    self.wolf.seteyeview(self.terrain.terraingroup)
    self.wolf.setscentview(self.beaver)
    #self.wolfsprite.update()

    marsh = self.terrain.getmarsh()
    if (self.beaver.action == Constants.BEAVER_ACTION_DROP_LUMBER and
        self.beaver.droppedlumber and
        pygame.sprite.collide_rect(self.beaver, marsh)):
      marsh.improve()
    marsh.update()

    # Reset the wolf if it gets stuck in marsh
    if pygame.sprite.collide_rect(self.wolf, marsh):
      self.wolf.respawn()

    if (self.beaver.energy <= 0 or
      self.beaver.rect.colliderect(self.wolf.rect)):

      temp = pygame.time.get_ticks()
      # Only when beaver starves
      if self.beaver.energy <= 0:
        generationtimes.append("%d\t%d" % (self.beaver.generationcount,
                                           temp - self.generationtime))
      self.generationtime = temp

      self.beaver.respawn()
      self.brain.agent.learn()
      self.brain.agent.reset()



      if self.beaver.generationcount > NUM_GENERATIONS:
        self._running = False

      # Reset the wolf so that it seems as if time has passed
      # (aka wolf not lurking around marsh on beaver spawn)
      self.wolf.respawn()

      # Reset the environment so beavers start alike.
      marsh.respawn()
      self.terrain.respawntrees()

    else:
      tree = pygame.sprite.spritecollideany(self.beaver,
        self.terrain.gettreelist())
      if tree is not None and not isinstance(tree, Marsh):
        # Check beaver state
        if self.beaver.action == Constants.BEAVER_ACTION_EAT:
          tree.setstate(Constants.TREE_STATE_ATE)
          tree.update()
        elif (self.beaver.action == Constants.BEAVER_ACTION_PICK_UP_LUMBER and
              self.beaver.pickeduplumber):
          tree.setstate(Constants.TREE_STATE_FORAGED)
          tree.update()

        # Check tree state
        if tree.health <= 0:
          self.terrain.respawntree(tree)

  def on_render(self):
    self.background.fill(BG_COLOR)
    self.screen.blit(self.background, (0, 0))

    # Draws beaver, wolf, marsh, and tree sprites
    self.terrain.terraingroup.draw(self.screen)
    self.beaversprite.draw(self.screen)
    self.wolfsprite.draw(self.screen)

    # Draws energy and health bars of beaver and trees
    bx, by = self.beaver.rect.topleft
    brect = pygame.Rect(bx, by, self.beaver.energybar, HEALTHBAR_HEIGHT)
    pygame.draw.rect(self.screen, HEALTHBAR_COLOR, brect, 0)

    for sprite in self.terrain.terraingroup:
      sx, sy = sprite.rect.topleft
      srect = pygame.Rect(sx, sy, sprite.healthbar, HEALTHBAR_HEIGHT)
      pygame.draw.rect(self.screen, HEALTHBAR_COLOR, srect, 0)

    # Inefficient but works w/o hacking up a blit function for transparent imgs
    pygame.display.update()
    self._clock.tick(FRAMERATE)

  def on_cleanup(self):
    pygame.quit()

  def on_execute(self):
    if self.on_init() == False:
      self._running = False

    while (self._running):
      for event in pygame.event.get():
        self.on_event(event)
      self.on_loop()
      self.on_render()
    self.on_cleanup()
class Simulation:
    sheep_list = []
    wolf = None
    turns_number = None
    sheep_number = None
    alive_sheep_number = None
    eaten_sheep_list = []
    json_data = []
    write_data = Data()
    wait_character = None

    def __init__(self, init_pos_limit, sheep_move_dist, wolf_move_dist,
                 sheep_number, turns_number, wait):
        log = "Info level: Setting simulation details " + str(init_pos_limit) + " " + str(sheep_move_dist) + " " + \
              str(wolf_move_dist) + " " + str(sheep_move_dist) + " " + str(sheep_number) + " " + str(turns_number) + " "
        logging.info(log)
        self.turns_number = turns_number
        self.wolf = Wolf(wolf_move_dist)
        self.wait_character = wait
        self.sheep_number = sheep_number
        self.alive_sheep_number = sheep_number
        for _ in range(sheep_number):
            self.sheep_list.append(Sheep(init_pos_limit, sheep_move_dist))

    def start_simulation(self):
        log = "Debug level: start_simulation "
        logging.debug(log)
        for i in range(self.turns_number):
            if self.alive_sheep_number == 0:
                return
            self.sheep_move()
            if self.wolf_attack():
                self.wolf_move()
            print("Tur: " + str(i) + ", wolf position: " +
                  str("{:.3f}".format(self.wolf.x_position)) + " " +
                  str("{:.3f}".format(self.wolf.y_position)))
            print("Sheep number: " + str(self.alive_sheep_number) +
                  ",eaten sheep: " + str(self.eaten_sheep_list))
            self.write_data.add_json_data(i, self.wolf.x_position,
                                          self.wolf.y_position,
                                          self.alive_sheep_number,
                                          self.sheep_list)
            self.write_data.add_csv_data(
                [str(i), str(self.alive_sheep_number)])
            input_character = ""
            log = "Info level: End of the round"
            logging.info(log)
            while input_character != self.wait_character:
                input_character = input()

    def sheep_move(self):
        log = "Debug level: sheep_move "
        logging.debug(log)

        for i in range(self.sheep_number):
            if self.sheep_list[i].alive:
                self.sheep_list[i].move()

    def wolf_move(self):
        log = "Debug level: wolf_move "
        logging.debug(log)
        i = self.closed_sheep()
        dist = self.sheep_from_wolf_distance(self.sheep_list[i])
        delta_x = abs(self.wolf.x_position - self.sheep_list[i].x_position)
        delta_y = abs(self.wolf.y_position - self.sheep_list[i].y_position)
        x = (self.wolf.wolf_move_dist * delta_x) / dist
        y = (self.wolf.wolf_move_dist * delta_y) / dist
        if self.wolf.x_position > self.sheep_list[i].x_position:
            x = -x
        if self.wolf.y_position > self.sheep_list[i].y_position:
            y = -y
        log = "Info level: Calculating wolf move"
        logging.info(log)
        self.wolf.move(x, y)

        return

    def wolf_attack(self):
        for i in range(self.sheep_number):
            if self.sheep_list[i].alive:
                if self.wolf.wolf_move_dist >= \
                        self.sheep_from_wolf_distance(self.sheep_list[i]):
                    self.alive_sheep_number -= 1
                    self.eaten_sheep_list.append(i)
                    self.sheep_list[i].alive = False
                    self.wolf.set_wolf_position(self.sheep_list[i].x_position,
                                                self.sheep_list[i].y_position)
                    log = "Debug level: wolf_attack " + "False"
                    logging.debug(log)
                    log = "Info level: Wolf can eat sheep"
                    logging.info(log)
                    return False
        log = "Info level: Wolf can't eat sheep"
        logging.info(log)
        log = "Debug level: wolf_attack " + "True"
        logging.debug(log)
        return True

    def closed_sheep(self):
        dist = 0
        sheep = None
        for i in range(self.sheep_number):
            if self.sheep_list[i].alive:
                dist = self.sheep_from_wolf_distance(self.sheep_list[i])
                sheep = i
                break
        for i in range(self.sheep_number):
            if self.sheep_list[i].alive:
                if dist > self.sheep_from_wolf_distance(self.sheep_list[i]):
                    dist = self.sheep_from_wolf_distance(self.sheep_list[i])
                    sheep = i
        log = "Info level: Finding the closed  sheep " + str(sheep)
        logging.info(log)
        log = "Debug level: closed_sheep " + str(sheep)
        logging.debug(log)
        return sheep

    def sheep_from_wolf_distance(self, sheep):
        log = "Info level: Calculating distance between the closed sheep and wolf " +\
              str(sqrt((sheep.x_position - self.wolf.x_position) * (sheep.x_position - self.wolf.x_position) +
                       (sheep.y_position - self.wolf.y_position) * (sheep.y_position - self.wolf.y_position)))
        logging.info(log)
        log = "Debug level: sheep_from_wolf_distance " + \
              str(sqrt((sheep.x_position - self.wolf.x_position) * (sheep.x_position - self.wolf.x_position) +
                       (sheep.y_position - self.wolf.y_position) * (sheep.y_position - self.wolf.y_position)))
        logging.debug(log)
        return sqrt((sheep.x_position - self.wolf.x_position) *
                    (sheep.x_position - self.wolf.x_position) +
                    (sheep.y_position - self.wolf.y_position) *
                    (sheep.y_position - self.wolf.y_position))
Beispiel #17
0
class GUI:
    def __init__(self):
        # tworzenie okna:
        self.window = Tk()
        self.window.title("Python 3 Simulation")
        self.window.geometry('500x420')
        self.window.resizable(False, False)
        self.window.configure(background="grey")

        # atrybuty instancyjne:

        # zmienna z kolorem tła:
        self.bg_color = "chartreuse2"

        self.init_pos_limit = 200.0

        # tworzymy obszar, ktory bedzie łaką (meadow)
        self.meadow = Canvas(self.window,
                             bg=self.bg_color,
                             height=1.5 * self.init_pos_limit,
                             width=1.5 * self.init_pos_limit)

        # suwak do przyblizania / oddalania
        self.scale_variable = DoubleVar()
        self.scale = Scale(self.window,
                           variable=self.scale_variable,
                           command=self.zooming,
                           activebackground="green",
                           bg="white",
                           from_=0,
                           to=5,
                           label="ZOOM")

        # wartosc domyslna dla suwaka
        self.default_value = 0
        # ustawiamy na początku na 0
        self.scale.set(self.default_value)

        # tworzymy wilka na start na srodku laki
        self.wolf = Wolf()
        self.drawn_wolf = draw_wolf(self.meadow, 145, 145,
                                    self.wolf.wolf_color, self.scale_variable)

        # owca, ktora nie jest pokazywana na lace
        self.sheep = Sheep(0, 100, 100)
        self.sheep_color = "light blue"

        # utworzenie obiektu lista owiec
        self.sheep_list_object = sheepsList.SheepList()
        self.sheep_list_gui = self.sheep_list_object.sheep_list
        self.points_list_gui = self.sheep_list_object.points_list

        # etykieta z liczba zywych owiec i zmienna do zmiany wartosci
        self.variable_sheep_number = StringVar()
        self.variable_sheep_number.set("0")
        self.label_how_many_sheep = Label(
            self.window,
            textvariable=self.variable_sheep_number,
            bg="grey",
            font="calibri 20 bold")

        # menu
        self.menu_bar = Menu(self.window)

        # przycisk step
        self.step = Button(self.window,
                           text="STEP",
                           height=2,
                           width=15,
                           justify=CENTER,
                           bg="white",
                           font="calibri 10 bold",
                           command=self.step)

        # przycisk Reset
        self.reset = Button(self.window,
                            text="RESET",
                            height=2,
                            width=15,
                            justify=CENTER,
                            bg="white",
                            font="calibri 10 bold",
                            command=self.reset)

        # przycisk start/stop
        self.var = StringVar()
        self.var.set("START")
        self.start_stop = Button(self.window,
                                 textvariable=self.var,
                                 height=2,
                                 width=15,
                                 justify=CENTER,
                                 bg="white",
                                 font="calibri 10 bold",
                                 command=self.start_stop_click)

        # zmienna dla czasu pojedynczego ruchu
        self.interval = 1.0

        # flaga do tego czy ruch ma trwać
        self.perform_flag = False

    # funkcja inicjalizujaca, ktora stworzy nam interfejs graficzny
    def initialization(self):
        # czyszczenie zawartosci listy owiec, zeby po ponownym otwarciu aplikacji byla pusta
        self.sheep_list_gui.clear()
        self.points_list_gui.clear()

        self.add_canvas()
        self.add_buttons()
        self.add_menu()

        self.window.mainloop()

    def save_to_file(self):
        # dodatkowa zmienna, zeby domyslnie otwieral sie biezacy katalog
        path = os.getcwd()
        f = filedialog.asksaveasfile(initialdir=path,
                                     title="Save file",
                                     filetypes=[('Json File', ['.json'])])
        # list_for_export_to_json - slownik, który wyeksportujemy do pliku json
        list_for_export_to_json = prepare_list_to_export_to_json(
            self.wolf, self.sheep_list_gui, self.sheep_color, self.bg_color)
        if f is None:  # jesli sie zamknie okno, to wtedy asksaveasfile zwraca None
            return
        export_to_json(list_for_export_to_json, f)

    def set_colors_from_file(self):
        self.meadow.configure(bg=self.bg_color)
        # pobieramy liste punktow, a nastepnie zmieniamy ich kolor
        points_list = self.sheep_list_object.get_points()
        for point in points_list:
            self.meadow.itemconfig(point, fill=self.sheep_color)
        self.variable_sheep_number.set(
            str(self.sheep_list_object.count_alive_sheeps()))

    def open_file(self):
        # dodatkowa zmienna, zeby domyslnie otwieral sie biezacy katalog
        path = os.getcwd()
        # funkcja do wybierania pliku do otwarcia
        # askopenfile zwraca wlasciwy plik, a askopenfilename zwrociloby sciezke do tego pliku
        f = filedialog.askopenfilename(initialdir=path,
                                       title="Select file",
                                       filetypes=[('Json File', ['.json'])])
        if f is None:  # jesli sie zamknie okno, to wtedy askopen file zwraca None
            return
        self.sheep_color, self.wolf, self.drawn_wolf, self.bg_color = import_from_json(
            f, self.meadow, self.scale_variable, self.sheep_list_gui,
            self.points_list_gui)
        self.scale.set(0)
        self.set_colors_from_file()

    def settings(self):
        # tutaj nowe okno do ustawien
        settings = Tk()
        settings.title("Settings")
        settings.geometry('300x210')
        settings.resizable(False, False)

        def paint_wolf_settings():
            # kolor to lista z dwoma elementami, pierwszy to informacje numeryczne w skali RGB, a drugi to kolor w
            # formacie szesnastkowym
            my_color = colorchooser.askcolor()[1]
            setattr(self.wolf, 'wolf_color', my_color)
            wolf_btn.configure(bg=self.wolf.wolf_color)
            self.meadow.itemconfig(self.drawn_wolf, fill=self.wolf.wolf_color)

        def paint_sheep_settings():
            # kolor to lista z dwoma elementami, pierwszy to informacje numeryczne w skali RGB, a drugi to kolor w
            # formacie szesnastkowym
            my_color = colorchooser.askcolor()[1]
            self.sheep_color = my_color
            sheep_btn.configure(bg=self.sheep_color)
            # pobieramy liste punktow, a nastepnie zmieniamy ich kolor
            points_list = self.sheep_list_object.get_points()
            for point in points_list:
                self.meadow.itemconfig(point, fill=self.sheep_color)
            for sheep in self.sheep_list_gui:
                sheep.sheep_color = self.sheep_color

        def paint_background_settings():
            # kolor to lista z dwoma elementami, pierwszy to informacje numeryczne w skali RGB, a drugi to kolor w
            # formacie szesnastkowym
            my_color = colorchooser.askcolor()[1]
            self.bg_color = my_color
            background_button.configure(
                bg=self.bg_color)  # tu moze trzeba self.bgColor
            self.meadow.configure(bg=self.bg_color)

        # ustawiamy pauze
        def set_interval(event):
            self.interval = float(chosen_number.get())

        wolf_label = Label(settings, text=" Wolf color ")
        wolf_label.place(x=20, y=20)

        wolf_btn = Button(settings,
                          text="Choose a color",
                          command=paint_wolf_settings,
                          bg=self.wolf.wolf_color)
        wolf_btn.place(x=190, y=20)

        sheep_label = Label(settings, text=" Sheep color ")
        sheep_label.place(x=20, y=50)

        sheep_btn = Button(settings,
                           text="Choose a color",
                           command=paint_sheep_settings,
                           bg=self.sheep_color)
        sheep_btn.place(x=190, y=50)

        background_label = Label(settings, text=" Background color ")
        background_label.place(x=20, y=80)

        background_button = Button(settings,
                                   text="Choose a color",
                                   command=paint_background_settings,
                                   bg=self.bg_color)
        background_button.place(x=190, y=80)

        time_label = Label(settings, text=" Single step time ")
        time_label.place(x=20, y=110)

        chosen_number = ttk.Combobox(settings,
                                     width=11)  # textvariable=self.number_var)
        chosen_number['justify'] = CENTER
        chosen_number['values'] = (0.5, 1, 1.5, 2)
        chosen_number.place(x=190, y=110)
        # ustawiamy index, na którym domyślnie ma byc ustawiony combobox po włączeniu ustawień
        pom = self.interval
        print(pom)
        if self.interval == 0.5:
            index = 0
        elif self.interval == 1.0:
            index = 1
        elif self.interval == 1.5:
            index = 2
        else:
            index = 3
        chosen_number.current(index)
        chosen_number.bind("<<ComboboxSelected>>", set_interval)

        # zmienna potrzebna pozniej do kontroli symulacji
        self.number_var = chosen_number.get()
        settings.mainloop()

    def add_menu(self):
        # Tworzenie paska menu
        self.window.config(menu=self.menu_bar)

        # Tworzenie menu a dodawanie do niego elementow
        # Pierwszy element z rozwijana lista
        menu_file = Menu(self.menu_bar, tearoff=0)
        menu_file.add_command(label="Open", command=self.open_file)
        menu_file.add_separator()
        menu_file.add_command(label="Save", command=self.save_to_file)
        menu_file.add_separator()
        menu_file.add_command(label="Quit", command=self.window.destroy)
        self.menu_bar.add_cascade(label="File", menu=menu_file)

        # Drugi element z rozwijana lista
        self.menu_bar.add_command(label="Settings", command=self.settings)

    def paint_sheep(self, event):
        x1, y1 = event.x, event.y
        point = draw_sheep(self.meadow, x1, y1, self.sheep_color,
                           self.scale_variable)
        # zmienna do numerowania owiec
        number = self.sheep_list_object.count()
        # dodanie owcy do listy owiec
        self.sheep_list_object.sheep_add(Sheep(number, x1, y1))
        self.sheep_list_gui[-1].sheep_color = self.sheep_color
        # dodanie narysowanego punktu oznaczajacego owce do listy narysowanych punktow w obiekcie klasy SheepsList
        self.sheep_list_object.point_add(point)
        # aktualizacja etykiety z lista zywych owiec na podstawie liczby elementow listy owiec
        self.variable_sheep_number.set(
            str(self.sheep_list_object.count_alive_sheeps()))

    def move_wolf(self, event):
        x1, y1 = event.x, event.y
        # usuwany jest istniejacy wilk
        self.meadow.delete(self.drawn_wolf)
        # i rysowany nowy na podstawie wspolrzednych pobranych z klikniecia uzytkownika
        self.drawn_wolf = draw_wolf(self.meadow, x1, y1, self.wolf.wolf_color,
                                    self.scale_variable)
        # zmiana wartosci wspolrzednych wilka w logice aplikacji
        self.wolf.x = x1
        self.wolf.y = y1

    def add_canvas(self):
        self.meadow.place(x=20, y=20)
        self.meadow.bind("<ButtonPress-1>", self.paint_sheep)
        self.meadow.bind("<ButtonPress-3>", self.move_wolf)

    # funkcja wykonujaca pojedyncza ture ruchow (czyli de facto step)
    def perform_move(self):

        # ruch owiec
        self.sheep_list_object.sheep_move()

        # obliczenie indeksu najblizszej owcy i wartosci tej odleglosci
        index_of_sheep_with_nearest_distance, nearest_distance \
            = self.sheep_list_object.find_nearest_distance(self.wolf)

        # ruch wilkiem (zmiana wspolrzednych na liscie)
        self.wolf.wolf_move(index_of_sheep_with_nearest_distance,
                            nearest_distance, self.sheep_list_gui,
                            self.points_list_gui, self.wolf, self.meadow)
        # ruch wilkiem na lace (narysowanie kropki w innym miejscu)
        self.meadow.delete(self.drawn_wolf)

        # rysowanie owiec po ruchu
        self.sheep_list_object.sheep_draw_all(self.meadow, self.scale_variable)

        # rysowanie wilka po ruchu owiec
        self.drawn_wolf = draw_wolf(self.meadow, self.wolf.x, self.wolf.y,
                                    self.wolf.wolf_color, self.scale_variable)

        # aktualizacja do etykiety wyswietlajacej zywe owce
        self.variable_sheep_number.set(
            str(self.sheep_list_object.count_alive_sheeps()))

    def step(self):
        if self.sheep_list_object.count_alive_sheeps() != 0:
            self.perform_move()

        else:
            messagebox.showerror(
                "Error",
                "There is no simulation step, because there are no sheeps in the meadow. "
                "\nAdd sheep and try again!")

    def reset(self):
        # usuniecie wszytskich owiec z listy
        self.sheep_list_gui.clear()
        # usuniecie wszytkich punktow z listy
        self.points_list_gui.clear()
        # czyszczenie laki ze wszystkich elementow
        self.meadow.delete("all")
        # ustawienie wilka na srodku
        self.drawn_wolf = draw_wolf(self.meadow, 145, 145,
                                    self.wolf.wolf_color, self.scale_variable)
        # ustawienie ponownie wspolrzednych wilka na srodek laki
        self.wolf.x = 145
        self.wolf.y = 145
        # ustawienie liczby zywych owiec na zero
        self.variable_sheep_number.set("0")

    def do_nothing(self, event):
        pass

    def start_stop_click(self):
        # warunki, zeby nazwa przycisku sie zmieniala po nacisnieciu
        if self.start_stop.cget("text") == "START":
            self.var.set("STOP")

            # zablokowanie pozostalych przyciskow
            self.step["state"] = DISABLED
            self.reset["state"] = DISABLED

            # zablokowanie paska menu
            self.menu_bar.entryconfig("File", state="disabled")
            self.menu_bar.entryconfig("Settings", state="disabled")

            # zablokowanie mozliwosci dodawania owiec oraz przesuwania wilka
            self.meadow.bind("<ButtonPress-1>", self.do_nothing)
            self.meadow.bind("<ButtonPress-3>", self.do_nothing)

            self.perform_flag = True

            if self.sheep_list_object.count_alive_sheeps() == 0:
                messagebox.showerror(
                    "Add sheep",
                    "There are no sheep on the meadow \n Add some")
            else:
                while self.sheep_list_object.count_alive_sheeps(
                ) != 0 and self.perform_flag:
                    self.perform_move()
                    self.window.update()
                    sleep(float(self.interval))
                    if self.sheep_list_object.count_alive_sheeps() == 0:
                        messagebox.showinfo(
                            "Game over",
                            "Wolf ate all sheep ;( \n Game is over.")
                        self.stop_game()
                        break
        else:
            self.stop_game()

    def stop_game(self):
        self.var.set("START")

        # odblokowanie pozostaych przyciskow
        self.step["state"] = NORMAL
        self.reset["state"] = NORMAL

        # odblokowanie paska menu
        self.menu_bar.entryconfig("File", state="normal")
        self.menu_bar.entryconfig("Settings", state="normal")

        # ponowne umozliwienie dodawania owiec oraz przesuwania wilka
        self.meadow.bind("<ButtonPress-1>", self.paint_sheep)
        self.meadow.bind("<ButtonPress-3>", self.move_wolf)

        self.perform_flag = False

    def add_buttons(self):
        # etykiety potrzebne do wyswietlenia ilosci owiec
        how_many_label = Label(self.window,
                               text="Number of live sheep: ",
                               bg="grey",
                               fg="white",
                               font="calibri 12 bold")
        how_many_label.place(x=335, y=20)

        self.label_how_many_sheep.place(x=400, y=40)

        # przycisk Step
        self.step.place(x=350, y=120)
        self.reset.place(x=350, y=180)

        # przycik Start/Stop
        self.start_stop.place(x=350, y=240)

        # suwak do przyblizania / oddalania
        self.scale.place(x=350, y=290)

    def zooming(self, event):
        # metoda do zoomowania (wzgledem srodka)
        # przyblizanie
        if float(event) > float(self.default_value):
            print(self.meadow.winfo_id())
            while float(event) > float(self.default_value):
                # self.meadow.scale("all", self.meadow.winfo_width() / 2, self.meadow.winfo_height() / 2,
                #                   1.25, 1.25)
                for point in self.points_list_gui:
                    self.meadow.delete(point)

                # pętla, w której ponownie rysujemy owce
                for sheep in self.sheep_list_gui:
                    if sheep.status == 'alive':
                        point = draw_sheep(self.meadow, sheep.x, sheep.y,
                                           sheep.sheep_color,
                                           self.scale_variable)
                        self.sheep_list_object.point_add(point)

                self.meadow.delete(self.drawn_wolf)
                self.drawn_wolf = draw_wolf(self.meadow, self.wolf.x,
                                            self.wolf.y, self.wolf.wolf_color,
                                            self.scale_variable)
                self.default_value = self.default_value + 1.0
        # oddalanie
        elif float(event) < float(self.default_value):
            while float(event) < float(self.default_value):
                # self.meadow.scale("all", self.meadow.winfo_width() / 2, self.meadow.winfo_height() / 2,
                #                   0.8, 0.8)
                for point in self.points_list_gui:
                    self.meadow.delete(point)

                    # pętla, w której ponownie rysujemy owce
                for sheep in self.sheep_list_gui:
                    if sheep.status == 'alive':
                        point = draw_sheep(self.meadow, sheep.x, sheep.y,
                                           sheep.sheep_color,
                                           self.scale_variable)
                        self.sheep_list_object.point_add(point)

                self.meadow.delete(self.drawn_wolf)
                self.drawn_wolf = draw_wolf(self.meadow, self.wolf.x,
                                            self.wolf.y, self.wolf.wolf_color,
                                            self.scale_variable)
                self.default_value = self.default_value - 1.0

        self.default_value = float(event)
Beispiel #18
0
    def __init__(self):
        # tworzenie okna:
        self.window = Tk()
        self.window.title("Python 3 Simulation")
        self.window.geometry('500x420')
        self.window.resizable(False, False)
        self.window.configure(background="grey")

        # atrybuty instancyjne:

        # zmienna z kolorem tła:
        self.bg_color = "chartreuse2"

        self.init_pos_limit = 200.0

        # tworzymy obszar, ktory bedzie łaką (meadow)
        self.meadow = Canvas(self.window,
                             bg=self.bg_color,
                             height=1.5 * self.init_pos_limit,
                             width=1.5 * self.init_pos_limit)

        # suwak do przyblizania / oddalania
        self.scale_variable = DoubleVar()
        self.scale = Scale(self.window,
                           variable=self.scale_variable,
                           command=self.zooming,
                           activebackground="green",
                           bg="white",
                           from_=0,
                           to=5,
                           label="ZOOM")

        # wartosc domyslna dla suwaka
        self.default_value = 0
        # ustawiamy na początku na 0
        self.scale.set(self.default_value)

        # tworzymy wilka na start na srodku laki
        self.wolf = Wolf()
        self.drawn_wolf = draw_wolf(self.meadow, 145, 145,
                                    self.wolf.wolf_color, self.scale_variable)

        # owca, ktora nie jest pokazywana na lace
        self.sheep = Sheep(0, 100, 100)
        self.sheep_color = "light blue"

        # utworzenie obiektu lista owiec
        self.sheep_list_object = sheepsList.SheepList()
        self.sheep_list_gui = self.sheep_list_object.sheep_list
        self.points_list_gui = self.sheep_list_object.points_list

        # etykieta z liczba zywych owiec i zmienna do zmiany wartosci
        self.variable_sheep_number = StringVar()
        self.variable_sheep_number.set("0")
        self.label_how_many_sheep = Label(
            self.window,
            textvariable=self.variable_sheep_number,
            bg="grey",
            font="calibri 20 bold")

        # menu
        self.menu_bar = Menu(self.window)

        # przycisk step
        self.step = Button(self.window,
                           text="STEP",
                           height=2,
                           width=15,
                           justify=CENTER,
                           bg="white",
                           font="calibri 10 bold",
                           command=self.step)

        # przycisk Reset
        self.reset = Button(self.window,
                            text="RESET",
                            height=2,
                            width=15,
                            justify=CENTER,
                            bg="white",
                            font="calibri 10 bold",
                            command=self.reset)

        # przycisk start/stop
        self.var = StringVar()
        self.var.set("START")
        self.start_stop = Button(self.window,
                                 textvariable=self.var,
                                 height=2,
                                 width=15,
                                 justify=CENTER,
                                 bg="white",
                                 font="calibri 10 bold",
                                 command=self.start_stop_click)

        # zmienna dla czasu pojedynczego ruchu
        self.interval = 1.0

        # flaga do tego czy ruch ma trwać
        self.perform_flag = False
Beispiel #19
0
def main():

    # default params init
    init_pos_limit = 10.0
    epochs = 50
    sheep_count = 15
    sheep_move_dist = 0.5
    wolf_move_dist = 1.0

    log_lvl = None

    # sheep list
    flock = []

    # sheep positions
    sheep_pos = []

    # file data
    json_data = []
    csv_data = []

    # path to pos.json and alive.csv files
    data_dir = os.getcwd()

    # parse arguments
    parser = argparse.ArgumentParser()
    parser.add_argument('-c',
                        '--config',
                        type=file_type,
                        metavar='FILE',
                        help='specify config file with initial values',
                        dest='conf_file')
    parser.add_argument(
        '-d',
        '--dir',
        type=dir_type,
        metavar='DIR',
        help='specify path to catalog that holds generated files',
        dest='data_dir')
    parser.add_argument(
        '-l',
        '--log',
        type=int,
        metavar='LEVEL',
        help=
        'choose level of logs saved in chase.log file: 10: DEBUG, 20: INFO, '
        '30: WARNING, 40: ERROR, 50: CRITICAL',
        dest='log_lvl')
    parser.add_argument('-r',
                        '--rounds',
                        type=int,
                        metavar='NUM',
                        help='specify max number of iterations',
                        dest='rounds_no')
    parser.add_argument('-s',
                        '--sheep',
                        type=int,
                        metavar='NUM',
                        dest='sheep_no',
                        help='specify number of sheep in flock')
    parser.add_argument(
        '-w',
        '--wait',
        action='store_true',
        dest='wait_flag',
        help='wait for user at the end of each round to continue')
    parser.add_argument('-q',
                        '--quiet',
                        action='store_false',
                        dest='quiet_flag',
                        help='do not print info in terminal')
    args = parser.parse_args()

    # check optional args
    wait_flag = args.wait_flag
    print_flag = args.quiet_flag

    if args.data_dir:
        data_dir = os.path.join(data_dir, args.data_dir)

    if args.log_lvl:
        for lvl in [10, 20, 30, 40, 50]:
            if args.log_lvl == lvl:
                log_lvl = lvl

        if log_lvl is None:
            raise ValueError('no such level: ' + str(args.log_lvl))

        print(os.path.join(data_dir, 'chase.log'))

        logging.basicConfig(filename=os.path.join(data_dir, 'chase.log'),
                            filemode='w',
                            level=log_lvl)

    if args.conf_file:
        config = configparser.ConfigParser()
        config.read(args.conf_file)

        terrain = config['Terrain']
        movement = config['Movement']

        if float(terrain['InitPosLimit']) < 0:
            logging.critical(
                'ValueError raised: incorrect value in InitPosLimit config file'
            )
            raise ValueError('negative value in config file: InitPosLimit')

        if float(movement['SheepMoveDist']) < 0:
            logging.critical(
                'ValueError raised: incorrect value in SheepMoveDist config file'
            )
            raise ValueError('negative value in config file: SheepMoveDist')

        if float(movement['WolfMoveDist']) < 0:
            logging.critical(
                'ValueError raised: incorrect value in WolfMoveDist config file'
            )
            raise ValueError('negative value in config file: WolfMoveDist')

        init_pos_limit = float(terrain['InitPosLimit'])
        sheep_move_dist = float(movement['SheepMoveDist'])
        wolf_move_dist = float(movement['WolfMoveDist'])

    if args.rounds_no:
        if args.rounds_no > 0:
            epochs = args.rounds_no
        elif log_lvl is not None:
            logging.warning(
                'value passed by -r/--rounds is incorrect, continuing with default values'
            )

    if args.sheep_no:
        if args.sheep_no > 0:
            sheep_count = args.sheep_no
        elif log_lvl is not None:
            logging.warning(
                'value passed by -s/--sheep is incorrect, continuing with default values'
            )

    # animals init
    wolf = Wolf(wolf_move_dist)
    for round_no in range(sheep_count):
        flock.append(Sheep(sheep_move_dist, round_no, init_pos_limit))
        sheep_pos.append(flock[round_no].position)

    # log formatter
    epoch_log = '[{:2}]\twolf pos.: ({: >7.3f}, {: >7.3f})\tnumber of sheep: {:2}'
    eaten_log = '  •———— sheep [{:2}] is dead'
    tmp_str = epoch_log.format(0, wolf.position[0], wolf.position[1],
                               len(flock))
    if print_flag:
        print(tmp_str)
    logging.info(tmp_str)

    # wait for user input
    if wait_flag:
        input('Press enter to continue: ')

    # main loop
    for round_no in range(1, epochs + 1):

        # move and update sheep
        for sheep in flock:
            sheep.move()
            sheep_pos[sheep.id] = sheep.position

        # find closest sheep to wolf
        closest_sheep = flock[0]
        for sheep in flock:
            x = fun.calc_euclid_dist(wolf.position, sheep.position)
            if x < fun.calc_euclid_dist(wolf.position, closest_sheep.position):
                closest_sheep = sheep
        wolf.closest_sheep_pos = closest_sheep.position
        logging.info('sheep closest to wolf found ({})'.format(
            closest_sheep.position))

        # eat or chase sheep
        if fun.calc_euclid_dist(wolf.position,
                                closest_sheep.position) < wolf.move_dist:
            tmp_str = eaten_log.format(closest_sheep.id)
            if print_flag:
                print(tmp_str)
            logging.info(tmp_str)

            flock.remove(closest_sheep)
            sheep_pos[closest_sheep.id] = None
        else:
            wolf.move()
            logging.info('Wolf is chasing closest sheep')

        # print epoch summary
        tmp_str = epoch_log.format(round_no, wolf.position[0],
                                   wolf.position[1], len(flock))
        if print_flag:
            print(tmp_str)
        logging.info(tmp_str)

        # append data to csv file
        csv_data.append([round_no, len(flock)])

        # append data to json file
        cloned_sheep_pos_list = sheep_pos[:]
        json_data.append({
            'round_no': round_no,
            'wolf_pos': wolf.position,
            'sheep_pos': cloned_sheep_pos_list
        })

        # end loop if no sheep in flock
        if len(flock) < 1:
            logging.info('simulation ended: all sheep were eaten')
            break

        # wait for user input
        if wait_flag and input('Press enter to continue: ') == 'exit':
            logging.info('simulation ended: user stopped the simulation')
            break

    # write to json file
    with open(os.path.join(data_dir, 'pos.json'), mode='w',
              newline='') as json_file:
        json_file.write(json.dumps(json_data, indent=4))
        logging.info('data written to pos.json')

    # write to csv file
    with open(os.path.join(data_dir, 'alive.csv'), mode='w',
              newline='') as csv_file:
        writer = csv.writer(csv_file)
        writer.writerow(['epoch_no', 'living_sheep'])
        writer.writerows(csv_data)
        logging.info('data written to alive.csv')
Beispiel #20
0
# authenticate with twitter & wolfram alpha
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)


# grab all tweets with "#tweetthewolf"
cursor = tweepy.Cursor(api.search, q="tweetthewolf")
for status in cursor.items():

    try:
        print("TWEET: " + str(status.text))
        print("FROM:  " + str(status._json["user"]["screen_name"]))

        wolf = Wolf(WOLFRAM_KEY, status.text)
        print("REQUEST URL: " + wolf.result())

        res = wolf.request()["queryresult"]
        if res["success"] and res.get("pods"):
            answer = ""

            for pod in res["pods"]:
                if pod["subpods"][0]["plaintext"] and len(pod["subpods"][0]["plaintext"] + answer) < 110:
                    answer += pod["subpods"][0]["plaintext"] + "\n"


            # tag questioner in response
            answer = "@" + status._json["user"]["screen_name"] + " " + answer
            print("ANSWER: " + answer)