def add_fish(self): """ add 20 fish """ for i in range(0, 20): fish = Fish() fish.init_pos() fish.angle = randint(0, 360) fish.velocity = Vector(-3, 0).rotate(fish.angle) self.add_widget(fish) self.flock_list.append(fish)
def __init__(self): # color, pos_x, pos_y, width, height self.mOrangeFish = Fish((255, 152, 0), 50, 175, 175, 100) self.mGreyFish = Fish((96, 125, 139), 350, 130, 125, 200) self.mRedFish = Fish((183, 28, 28), 200, 300, 175, 500) # color, start-point x, start-point y, end-point x, end-point y, width self.mSeaweed = Seaweed((104, 159, 56), 450, 450, 450, 500, 3) self.mSeaweed2 = Seaweed((104, 159, 56), 400, 450, 400, 500, 3) self.mSeaweed3 = Seaweed((104, 159, 56), 370, 430, 370, 500, 3) self.mSeaweed4 = Seaweed((104, 159, 56), 390, 430, 390, 500, 3) self.mSeaweed5 = Seaweed((104, 159, 56), 320, 450, 320, 500, 3) return
class TestFish(unittest.TestCase): def setUp(self): self.constraint = (1000, 1000) self.fish = Fish(self.constraint, 100, 100, Directions.left, 1) def test_init_no_params(self): fish = Fish(self.constraint) self.assertEqual(fish.x, 0) self.assertEqual(fish.y, 0) self.assertEqual(fish.direction, (1, 0)) self.assertEqual(fish.size, 0) self.assertEqual(fish.image_size, 80) radius = (fish.size * 15 + 41) / 2 self.assertEqual(fish.radius, radius) self.assertFalse(fish.hungry) self.assertFalse(fish.dead) def test_init(self): self.assertEqual(self.fish.x, 100) self.assertEqual(self.fish.y, 100) self.assertEqual(self.fish.direction, Directions.left) self.assertEqual(self.fish.size, 1) radius = (self.fish.size * 15 + 41) / 2 self.assertEqual(self.fish.radius, radius) def test_starve(self): self.fish.starve() self.assertTrue(self.fish.dead) self.assertEqual(self.fish.state, 'die') self.assertFalse(self.fish.mirrored) self.assertEqual(self.fish.frame, 0) self.fish.mirrored = True self.fish.starve() self.assertEqual(self.fish.frame, 720) # # How to test time()??? works every 10 seconds.. # def test_hungry_check(self): # self.fish.last_fed = 9 # self.fish.hungry_check() # self.assertTrue(self.fish.hungry) def test_eat(self): food = 5 growth = self.fish.growth size = self.fish.size self.fish.eat(food) self.assertFalse(self.fish.hungry) self.assertEqual(self.fish.growth, growth + food) self.assertEqual(self.fish.size, size) self.fish.eat(food) self.assertNotEqual(self.fish.size, size)
def __init__(self, *args, **kwargs): self.size = (Window.width, Window.height) super(FishLifeGame, self).__init__(*args, **kwargs) self.victory_screen = FishLifeScore() self.manufacture_ships(3) self.fish = Fish(box=[self.game_area.x, self.game_area.y + 65, self.game_area.width, self.game_area.height - 175]) self.fish.bind(pos=lambda instance, value: self.check_for_smthing_to_eat(value)) self.fish.bind(calories=self.update_calories_bar) self.fish.bind(on_death=self.the_end)
def try_to_add_a_fish(): # Nie dodajemy nowych rybek do zakończonej gry. if Server.game_started is False: return # Nie dodajemy nowych rybek keżeli na planszy leży ich # wystarczająca ilość. if len(Server.board.fishes) >= Server.number_of_fishes: return # Wylosuj typ i położenie nowej rybki. type = Fish.random_type() position = Server.board.random_unoccupied_tile() # Utwórz rybkę i dodaj ją do planszy. fish = Fish(type, *position) Server.board.add_fish(fish) # Wyślij do wszystkich klientów powiadomienie o nowej rybce. self._send_to_all(NewFishMessage(fish))
class Water: def __init__(self): # color, pos_x, pos_y, width, height self.mOrangeFish = Fish((255, 152, 0), 50, 175, 175, 100) self.mGreyFish = Fish((96, 125, 139), 350, 130, 125, 200) self.mRedFish = Fish((183, 28, 28), 200, 300, 175, 500) # color, start-point x, start-point y, end-point x, end-point y, width self.mSeaweed = Seaweed((104, 159, 56), 450, 450, 450, 500, 3) self.mSeaweed2 = Seaweed((104, 159, 56), 400, 450, 400, 500, 3) self.mSeaweed3 = Seaweed((104, 159, 56), 370, 430, 370, 500, 3) self.mSeaweed4 = Seaweed((104, 159, 56), 390, 430, 390, 500, 3) self.mSeaweed5 = Seaweed((104, 159, 56), 320, 450, 320, 500, 3) return def draw(self, surface): color = (1, 87, 155) pointlist = [(0, 80), (100, 100), (200, 80), (300, 100), (400, 80), (500, 100), (600, 80), (600, 500), (0, 500)] pygame.draw.polygon(surface, color, pointlist, 0) self.mOrangeFish.draw(surface) self.mGreyFish.draw(surface) self.mRedFish.draw(surface) self.mSeaweed.draw(surface) self.mSeaweed2.draw(surface) self.mSeaweed3.draw(surface) self.mSeaweed4.draw(surface) self.mSeaweed5.draw(surface) return
def setUp(self): self.constraint = (1000, 1000) self.fish = Fish(self.constraint, 100, 100, Directions.left, 1)
class FishLifeGame(Widget): ships = ListProperty([]) fish = ObjectProperty(None) start_time = ObjectProperty(None) def __init__(self, *args, **kwargs): self.size = (Window.width, Window.height) super(FishLifeGame, self).__init__(*args, **kwargs) self.victory_screen = FishLifeScore() self.manufacture_ships(3) self.fish = Fish(box=[self.game_area.x, self.game_area.y + 65, self.game_area.width, self.game_area.height - 175]) self.fish.bind(pos=lambda instance, value: self.check_for_smthing_to_eat(value)) self.fish.bind(calories=self.update_calories_bar) self.fish.bind(on_death=self.the_end) def play(self, *largs): for ship in self.ships: self.drop_ship_onto_sea(ship) self.game_area.add_widget(self.fish, index=1) self.fish.active = True # Tick tock, the food is dropped \o ooops Clock.schedule_interval(self.drop_food, 2) # SAIL AWAY! Clock.schedule_interval(self.sail_ships, 5) # Lets try and not overheat the CPU ;) Clock.schedule_interval(self.check_for_smthing_to_eat, 0.4) self.start_time = datetime.now() def pause(self): Clock.unschedule(self.drop_food) Clock.unschedule(self.sail_ships) Clock.unschedule(self.check_for_smthing_to_eat) def the_end(self, instance): self.pause() self.victory_screen.calories_score.text = str(self.fish.total_calories) self.victory_screen.junk_score.text = str(self.fish.junk_swallowed) self.victory_screen.total_score.text = "On %s a fish was caught, size of %s, which well fed the people of the world for %s days straight!" % (datetime.now().strftime("%B %d, %Y"), self.fish.rank[self.fish.obese_lvl - 1], (datetime.now() - self.start_time).seconds ) self.add_widget(self.victory_screen) def manufacture_ships(self, count = 1): """Next batch coming for Somalia""" for n in range(0, count): ship = Ship(horison=self.horison) self.ships.append(ship) # *cough*workaround*cough* bind on first ship self.ships[0].bind(on_start_sailing=lambda instance: Clock.schedule_interval(self.drop_junk, 0.4)) self.ships[0].bind(on_stop_sailing=lambda instance: Clock.unschedule(self.drop_junk)) def drop_ship_onto_sea(self, ship): """Randomly throw away the dead meat! BUahaha""" try: if not ship: ship = self.ships.pop() self.game_area.add_widget(ship) ship.center_x = randint(0, Window.width - ship.width/4) ship.y = self.game_area.height ship.active = True except IndexError: Logger.debug("No ships left in dock.") def check_for_smthing_to_eat(self, dt): """Collision detection: leFish vs Food'n'Junk""" to_eat = [] for stuff in self.game_area.children: if stuff.collide_widget(self.fish): if isinstance(stuff, Food) or isinstance(stuff, Junk): to_eat.append(stuff) for shit in to_eat: self.game_area.remove_widget(shit) self.game_area.add_widget(FoodScoreFeedback(calories=shit.calories, center=shit.center)) self.fish.eat(shit) def drop_food(self, td): """Periodicaly drop food from the ships""" for ship in self.ships: food = Food(what="bottle", lvl=self.fish.obese_lvl, x = ship.center_x + randint(-50,50), y = ship.y + randint(-5,5)) def really_drop_food(food, td): self.game_area.add_widget(food) food.active = True Clock.schedule_once(partial(really_drop_food, food), random() * 2) def drop_junk(self, *args): """Feels sooooOOo goood yeaaahhhh""" for ship in self.ships: junk = Junk(lvl=self.fish.obese_lvl, x = ship.center_x + randint(-50,50), y = ship.y + randint(-5,5)) self.game_area.add_widget(junk) junk.active = True def sail_ships(self, timer): """I wonder, wheres the captain?""" for ship in self.ships: ship.sail() def update_calories_bar(self, instance, new_value): self.calories_bar.value = new_value
if args['logfile']: # Log to File fh = logging.FileHandler('scencode.log') fh.setLevel(logging.WARNING) fh.setFormatter(formatter) logger.addHandler(fh) if args['verbose']: # log to StdOut ch = logging.StreamHandler() ch.setLevel(logging.INFO) ch.setFormatter(formatter) logger.addHandler(ch) fish = Fish() frames = [] re_frame_number = re.compile('[0-9]+') ################################################################################ # waiting for the frames ################################################################################ print '\nSearching for "%s"' % args['path'] try: while not glob.glob(args['path']): fish.animate() time.sleep(0.0075) #print 'Frames found:'
playerAnimRight = Anim([graphics.crab1_right, graphics.crab2_right], 3) playerAnimIdle = Anim( [graphics.crab_idle1, graphics.crab_idle2, graphics.crab_idle1], 20) # Set up bubbles for i in range(6): startX = random.getrandbits(2) * 10 + 10 startY = 100 bubbleSpd = random.getrandbits(2) bubbleSize = random.getrandbits(2) bubbleList.append([startX, startY, bubbleSpd, bubbleSize]) bubbles = Bubbles(bubbleList) # Set up single fish fishList.append(Fish(random.getrandbits(1) + 1, random.getrandbits(2))) coinList.append( Coin(0, 89) ) # Nasty hack to spawn the initial coin, as you can't catch the first one!!!? # Start music tmusic.playMenuMusic(menuSong) #print ("free",gc.mem_free()) # Main loop while True: # Read keys eventtype = pygame.event.poll() if eventtype != pygame.NOEVENT: # Keydown events
def __init__(self, ecosystem, location=None, isNewborn=False): Fish.__init__(self, ecosystem, 19, 10, location, isNewborn) self.survivalProbability = 1 self.movementImpact = .75
def index(): print('游戏开始!') fishNum = 5 guiNum = 1 num = guiNum #存活的乌龟 liveAnim = list() #存活的动物 animloca = dict() #键值为姓名,值为坐标 #实例化 fishNum 个鱼 for i in range(fishNum): fobj = Fish('&&&' + str(i)) liveAnim.append(fobj) animloca.update({fobj.name: fobj.live()}) #实例化guiNum 个乌龟 for i in range(guiNum): #这里重复覆盖这个对象,不会影响到已经添加到list 里的已有对象 gobj = Wgui('@@@' + str(i)) liveAnim.append(gobj) animloca.update({str(gobj.name): gobj.live()}) while (num > 0) and (len(liveAnim) != 0): num = 0 #输出他们的状态 #上边界 for sfir in range(11): on = 0 for oneAnim in animloca.items(): if (oneAnim[1][1] == 0) and (oneAnim[1][0] == sfir): if '&' in str(oneAnim[0]): print('&&&', end='') else: print('@@@', end='') on = 1 #此位置被占 if on == 0: print('+++', end='') if sfir == 10: print() #中间输出1-9行 for fir in range(9): #控制左边边界 on = 0 for oneAnim in animloca.items(): if (oneAnim[1][0] == 0) and (oneAnim[1][1] == fir + 1): if '&' in str(oneAnim[0]): print('&&&', end='') else: print('@@@', end='') on = 1 if on == 0: print(' + ', end='') #控制中间空白的活动区域 for mid in range(9): on = 0 for oneAnim in animloca.items(): if (oneAnim[1][0] == mid + 1) and (oneAnim[1][1] == fir + 1): if '&' in str(oneAnim[0]): print('&&&', end='') else: print('@@@', end='') on = 1 if on == 0: print(' ', end='') #输出右边边界 on = 0 for oneAnim in animloca.items(): if (oneAnim[1][0] == 10) and (oneAnim[1][1] == fir + 1): if '&' in str(oneAnim[0]): print('&&&', end='') else: print('@@@', end='') on = 1 if on == 0: print(' + ', end='') print('') #输出下方边界 for xfir in range(11): on = 0 for oneAnim in animloca.items(): if (oneAnim[1][1] == 10) and (oneAnim[1][0] == xfir): if '&' in str(oneAnim[0]): print('&&&', end='') else: print('@@@', end='') on = 1 # 此位置被占 if on == 0: print('+++', end='') if xfir == 10: print() #对活着的动物进行检查 waitdead = list() for eachAn in liveAnim: noloca = eachAn.live() if noloca == (-1, -1): animloca.pop(str(eachAn.name)) #print(noloca.name+'死亡') #标记对象数组里待删除的对象序号 waitdead.append(liveAnim.index(eachAn)) else: animloca.update({eachAn.name: noloca}) for adead in waitdead: liveAnim.pop(adead) #重新记录,待删除的鱼(被吃掉) waitdead.clear() #对乌龟吃掉的鱼进行删除 i = 0 for eachAn1 in animloca.items(): j = 0 for aname in animloca.items(): #如果eachAn1 是鱼,aname是一个龟,并且坐标相等 if ('@@@' in str(aname[0])) and ('&&&' in str( eachAn1[0])) and (eachAn1[1] == aname[1]): waitdead.append(i) #liveAnim[i].setliveval() liveAnim[j].life += 1 j += 1 i += 1 for adead in waitdead: animloca.pop(liveAnim[adead].name) liveAnim[adead].setliveval() liveAnim.pop(adead) for liveWgui in liveAnim: if isinstance(liveWgui, Wgui): num += 1
class FishLifeGame(Widget): ships = ListProperty([]) fish = ObjectProperty(None) start_time = ObjectProperty(None) def __init__(self, *args, **kwargs): self.size = (Window.width, Window.height) super(FishLifeGame, self).__init__(*args, **kwargs) self.victory_screen = FishLifeScore() self.manufacture_ships(3) self.fish = Fish(box=[ self.game_area.x, self.game_area.y + 65, self.game_area.width, self.game_area.height - 175 ]) self.fish.bind( pos=lambda instance, value: self.check_for_smthing_to_eat(value)) self.fish.bind(calories=self.update_calories_bar) self.fish.bind(on_death=self.the_end) def play(self, *largs): for ship in self.ships: self.drop_ship_onto_sea(ship) self.game_area.add_widget(self.fish, index=1) self.fish.active = True # Tick tock, the food is dropped \o ooops Clock.schedule_interval(self.drop_food, 2) # SAIL AWAY! Clock.schedule_interval(self.sail_ships, 5) # Lets try and not overheat the CPU ;) Clock.schedule_interval(self.check_for_smthing_to_eat, 0.4) self.start_time = datetime.now() def pause(self): Clock.unschedule(self.drop_food) Clock.unschedule(self.sail_ships) Clock.unschedule(self.check_for_smthing_to_eat) def the_end(self, instance): self.pause() self.victory_screen.calories_score.text = str(self.fish.total_calories) self.victory_screen.junk_score.text = str(self.fish.junk_swallowed) self.victory_screen.total_score.text = "On %s a fish was caught, size of %s, which well fed the people of the world for %s days straight!" % ( datetime.now().strftime("%B %d, %Y"), self.fish.rank[self.fish.obese_lvl - 1], (datetime.now() - self.start_time).seconds) self.victory_screen.open() def manufacture_ships(self, count=1): """Next batch coming for Somalia""" for n in range(0, count): ship = Ship(horison=self.horison) self.ships.append(ship) # *cough*workaround*cough* bind on first ship self.ships[0].bind(on_start_sailing=lambda instance: Clock. schedule_interval(self.drop_junk, 0.4)) self.ships[0].bind( on_stop_sailing=lambda instance: Clock.unschedule(self.drop_junk)) def drop_ship_onto_sea(self, ship): """Randomly throw away the dead meat! BUahaha""" try: if not ship: ship = self.ships.pop() self.game_area.add_widget(ship) ship.center_x = randint(0, Window.width - ship.width / 4) ship.y = self.game_area.height ship.active = True except IndexError: Logger.debug("No ships left in dock.") def check_for_smthing_to_eat(self, dt): """Collision detection: leFish vs Food'n'Junk""" to_eat = [] for stuff in self.game_area.children: if stuff.collide_widget(self.fish): if isinstance(stuff, Food) or isinstance(stuff, Junk): to_eat.append(stuff) for shit in to_eat: self.game_area.remove_widget(shit) self.game_area.add_widget( FoodScoreFeedback(calories=shit.calories, center=shit.center)) self.fish.eat(shit) def drop_food(self, td): """Periodicaly drop food from the ships""" for ship in self.ships: food = Food(what="bottle", lvl=self.fish.obese_lvl, x=ship.center_x + randint(-50, 50), y=ship.y + randint(-5, 5)) def really_drop_food(food, td): self.game_area.add_widget(food) food.active = True Clock.schedule_once(partial(really_drop_food, food), random() * 2) def drop_junk(self, *args): """Feels sooooOOo goood yeaaahhhh""" for ship in self.ships: junk = Junk(lvl=self.fish.obese_lvl, x=ship.center_x + randint(-50, 50), y=ship.y + randint(-5, 5)) self.game_area.add_widget(junk) junk.active = True def sail_ships(self, timer): """I wonder, wheres the captain?""" for ship in self.ships: ship.sail() def update_calories_bar(self, instance, new_value): self.calories_bar.value = new_value
from fish import Fish from aquarium import Aquarium Clown_fish = Fish("Bob", 12, "Blue", False) Tang = Fish("Buddy", 13, "Orange", True) Kong = Fish("Patrick", 14, "Red", False) aquarium1 = Aquarium() aquarium1.add_fish([Clown_fish]) aquarium1.add_fish([Tang]) aquarium1.add_fish([Kong]) aquarium2 = Aquarium() aquarium2.add_fish([Clown_fish, Kong]) print(aquarium1.getstatus()) print(aquarium2.getstatus()) for i in range(len(aquarium1.list_of_fish)): print(aquarium1.list_of_fish[i].status()) for i in range(len(aquarium2.list_of_fish)): print(aquarium2.list_of_fish[i].status())
def enter(): global bgm,open_lock bgm = load_music('Resource\Sound\Background.mp3') open_lock=load_wav('Resource\Sound\Open_lock.wav') open_lock.set_volume(128) bgm.set_volume(30) bgm.repeat_play() global hero, tiles,fish,bird tiles= Tile() hero = HERO() fish = [Fish() for i in range(10)] bird =[Bird() for i in range(5)] global number number = [[0] * 60 for i in range(45)] for i in range(0,45): for j in range(0,60): if tiles.dungeon.level[i][j] is 'floor': number[i][j]=0 elif tiles.dungeon.level[i][j] is 'stone': number[i][j]=9 elif tiles.dungeon.level[i][j] is 'wall': number[i][j]=9 elif tiles.dungeon.level[i][j] is 'stair': number[i][j]=6 start = True while (start):#hero setting i = random.randint(0+1, 45 - 1) j = random.randint(0+1, 60 - 1) if number[i][j] is 0: hero.x = j * 50 hero.y = i * 50 number[i][j]=1 start = False for k in range(10): while(fish[k].setting is False): i = random.randint(0+1, 45 - 1) j = random.randint(0+1, 60 - 1) if number[i][j] is 0 and fish[k].setting is False: fish[k].x = j * 50 fish[k].y = i * 50 number[i][j] = 2 fish[k].setting=True for k in range(5): while(bird[k].setting is False): i = random.randint(0+1, 45 - 1) j = random.randint(0+1, 60 - 1) if number[i][j] is 0 and bird[k].setting is False: bird[k].x = j * 50 bird[k].y = i * 50 number[i][j] = 2 bird[k].setting=True game_world.add_object(tiles, 0) game_world.add_object(hero, 1) game_world.add_objects(fish,1) game_world.add_objects(bird,1) global mouse,keyboard mouse = keyboard_mouse.Mouse() keyboard=keyboard_mouse.Keyboard() game_world.add_object(mouse, 1) game_world.add_object(keyboard,1) hide_cursor()
class FredLifeGame(Widget): ships = ListProperty([]) fish = ObjectProperty(None) start_time = ObjectProperty(None) def __init__(self, *args, **kwargs): self.size = (Window.width, Window.height) super(FredLifeGame, self).__init__(*args, **kwargs) self.victory_screen = FredLifeScore() self.manufacture_ships(3) self.fish = Fish( box=[self.game_area.x, self.game_area.y + 65, self.game_area.width, self.game_area.height - 175]) self.fish.bind(pos=lambda instance, value: self.check_for_smthing_to_eat(value)) self.fish.bind(calories=self.update_calories_bar) self.fish.bind(on_death=self.the_end) def play(self, *largs): for ship in self.ships: self.drop_ship_onto_sea(ship) self.game_area.add_widget(self.fish, index=1) self.fish.active = True Clock.schedule_interval(self.drop_food, 4) Clock.schedule_interval(self.sail_ships, 4) Clock.schedule_interval(self.check_for_smthing_to_eat, 0.2) self.start_time = datetime.now() def pause(self): Clock.unschedule(self.drop_food) Clock.unschedule(self.sail_ships) Clock.unschedule(self.check_for_smthing_to_eat) def the_end(self, instance): self.pause() self.victory_screen.calories_score.text = str(self.fish.total_calories) self.victory_screen.junk_score.text = str(self.fish.junk_swallowed) self.victory_screen.open() def manufacture_ships(self, count=1): for n in range(0, count): ship = Ship(horison=self.horison) self.ships.append(ship) self.ships[0].bind(on_start_sailing=lambda instance: Clock.schedule_interval(self.drop_junk, 1)) self.ships[0].bind(on_stop_sailing=lambda instance: Clock.unschedule(self.drop_junk)) def drop_ship_onto_sea(self, ship): try: if not ship: ship = self.ships.pop() self.game_area.add_widget(ship) ship.center_x = randint(0, Window.width - ship.width / 4) ship.y = self.game_area.height ship.active = True except IndexError: Logger.debug("No ships left in dock.") def check_for_smthing_to_eat(self, dt): """Collision detection""" to_eat = [] for stuff in self.game_area.children: if stuff.collide_widget(self.fish): if isinstance(stuff, Food) or isinstance(stuff, Junk): to_eat.append(stuff) for shit in to_eat: self.game_area.remove_widget(shit) self.game_area.add_widget(FoodScoreFeedback(calories=shit.calories, center=shit.center)) self.fish.eat(shit) def drop_food(self, td): """Periodically drop food from the ships""" for ship in self.ships: food = Food(what="bottle", lvl=self.fish.obese_lvl, x=ship.center_x + randint(-50, 50), y=ship.y + randint(-5, 5)) def really_drop_food(food, td): self.game_area.add_widget(food) food.active = True Clock.schedule_once(partial(really_drop_food, food), random() * 2) def drop_junk(self, *args): """Periodically drop junk from the ships""" for ship in self.ships: junk = Junk(lvl=self.fish.obese_lvl, x=ship.center_x + randint(-50, 50), y=ship.y + randint(-5, 5)) self.game_area.add_widget(junk) junk.active = True def sail_ships(self, timer): for ship in self.ships: ship.sail() def update_calories_bar(self, instance, new_value): self.calories_bar.value = new_value
def main(): UDP_IP_ADDRESS = "127.0.0.1" UDP_PORT_NO = 6789 print("GOT IT") serverSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) serverSock.bind((UDP_IP_ADDRESS, UDP_PORT_NO)) # initialize the pygame module # create a surface on screen that has the size of 240 x 180 image = pygame.image.load("underwaterbg.jpg") image3 = pygame.image.load("fish1.png") # blit image to screen # define a variable to control the main loop running = True x_change = 0 #change in the x position of player1 x_change2 = 0 #change in the x position of player2 y_change = 0 #change in the y position of player1 y_change2 = 0 #change in the y position of player2 size = 1 #sample size of the fish all_sprites_list = pygame.sprite.Group() #creates a list of sprites block_list = pygame.sprite.Group() # playerFish = Fish(bright_blue, 45, 45) #parameters: (color of the rect, width, height) # playerFish.rect.x = 50 # initial x pos # playerFish.rect.y = 50 # initial y pos playerCar2 = Fish(bright_blue, 45, 45) playerCar2.rect.x = 100 playerCar2.rect.y = 50 # Add the car to the list of objects all_sprites_list.add(playerFish) all_sprites_list.add(playerCar2) block_list.add(playerCar2) for i in range(50): # This represents a block block = Fish(black, 20, 15) # Set a random location for the block block.rect.x = random.randrange(800) block.rect.y = random.randrange(521) # Add the block to the list of objects block_list.add(block) all_sprites_list.add(block) score = 0 # main loop while running: # only do something if the event is of type QUIT event = pygame.event.poll() if event.type == pygame.QUIT: # change the value to False, to exit the main loop running = False quit() playerFish.handle_keys() playerCar2.handle_keys() # data, addr = serverSock.recvfrom(1024) # print("Message: " + data.decode()) all_sprites_list.update() #updates the list with all the changes made. blocks_hit_list = pygame.sprite.spritecollide(playerFish, block_list, True) for block in blocks_hit_list: score += 1 getFishPoints(playerFish, score) print(score) # updates the background with the starting index in the window: (0,0) screen.blit(image, (0, 0)) all_sprites_list.draw( screen) #draws all the sprites that are inside the list # update the screen to make the changes visible (fullscreen update) pygame.display.update() # amount of time before the screen updates clock.tick(500)
def run_simulation(fishes=None, foods=None, n_pop=10, max_time=3000, verbose=True, size_w=(600, 900, 3), initial_simulation=False, epoch=None, record=False, ALIVE=False, folder='frames', num_food=None): global refPt #WORLD definition size_w = size_w size_w1, size_w2 = size_w[:2][::-1] #the world that the food percieve, it contains only the fishes food_world = (np.zeros(size_w) + (255, 255, 255)).astype(np.uint8) #the world that the fishes percieve, it contains only the food fish_world = 255 * np.ones(size_w, dtype=np.uint8) if initial_simulation and verbose: #tutorial cm_br = command_bridge(f_size=0.7, commands=[ 'd debug', 'e energy', 'click to focus on one', 'b to focus the best' 'esc to remove focus', 'h increse speed', 'k decrese speed', 'esc again to exit' ]) cv2.imshow('beginning', merge_images_h([cm_br])) res = cv2.waitKey(0) cv2.destroyAllWindows() # Mouse callback #refPt = (10,10) if verbose and not record: cv2.namedWindow("Simulation") cv2.setMouseCallback("Simulation", dclick) time = 0 max_radius = 40 n_pop = n_pop #30 s1 = 100 s2 = 100 fishes_pos_orient_color = [ ( rand.randint(s2, size_w2 - s2), #x rand.randint(s1, size_w1 - s1), #y 2 * pi * rand.random(), #orientation np.random.choice(range(256), size=3, replace=False) #,dtype=np.uint8)#color ) for i in range(n_pop) ] if fishes is None: fishes = [ Fish(orient=o, pos=(p1, p2), color=c) for p1, p2, o, c in fishes_pos_orient_color ] else: fishes = fishes #fishes = [Fish()] #,Fish(pos=(100,102),orient=pi*1)] if foods is None: if num_food is None: num_food = int(n_pop * 3 / 2) + 1 print(size_w1, size_w2) foods_pos_orient = np.array([ ( rand.randint(s2 + 1 + max_radius, size_w2 - s2 - 1 - max_radius), #0-900 rand.randint(s1 + 1 + max_radius, size_w1 - s1 - 1 - max_radius), #0-600 2 * pi * rand.random()) for i in range(num_food) ]) foods = [ AliveFood(pos=(p1, p2), orient=o) for p1, p2, o in foods_pos_orient ] else: foods = foods dead_foods = [] food_positions = np.array([f.pos for f in foods]) #.astype(np.uint8) # num_foods = [] alive = n_pop debug = False energy = False selected = None focus = False focus_best = focus food_focus = True food_selected = None while (time < max_time): #get focus on individual #subject to verbose if verbose: if refPt is not None: focus_best = False focus = True print('clicked on ', refPt[::-1]) all_dist = np.sqrt( np.sum((np.array( [f.pos + 1000 * (f.energy <= 0) for f in fishes]) - (refPt[::-1] + np.array([s1, s2])))**2, axis=1)) selected = fishes[np.argmin(all_dist)] refPt = None #food steps #create food #add food every 3 steps if (not ALIVE or False ) and time % 20 == 1: #and food_positions.shape[0]<3*alive: pos1, pos2, o = ( rand.randint(s2 + 1 + max_radius, size_w2 - s2 - 1 - max_radius), #0-900 rand.randint(s1 + 1 + max_radius, size_w1 - s1 - 1 - max_radius), #0-600 2 * pi * rand.random()) mind = int(rand.random()) if mind == 0 and len(dead_foods) > 0: pool = dead_foods else: pool = foods new_food = AliveFood(pos=(pos1, pos2), orient=o, mind=pool[rand.randint(0, len(pool) - 1)].mind) foods.append(new_food) #insert in array to calculate distancies food_positions = np.vstack([food_positions, [pos1, pos2]]) num_foods.append(len(food_positions)) #draw food fish_world = (np.zeros(size_w) + (255, 255, 255)).astype(np.uint8) for i, food in enumerate(foods): if ALIVE: food.get_perception(food_world) react = food.predict(food.to_feed) #if food==food_selected: #print(food.to_feed,react) food.turn(direction=react[0]) food.inc_speed(delta=react[1]) food.move(fish_world, dx=s1 - food.s1, dy=s2 - food.s2) food_positions[i] = food.pos food.outout = react food.draw(fish_world) food_world = (np.zeros(size_w) + (255, 255, 255)).astype(np.uint8) #reset food_world after that the fishes have been drawn s.t. the food can understand where they are # #get perceptions, calculate output # increase energy if eat somehtin for f in fishes: if f.energy > 0: #f.move(food_world,dx=s1-f.s1,dy=s2-f.s2) #getting perceptions f.get_perception(fish_world) #print(f.to_feed) react = f.predict(f.to_feed) f.outout = react f.turn(direction=react[0]) f.inc_speed(delta=react[1]) f.diversity_speed[int(np.sign(np.round(react[1], 1))) + 1] += 1 f.diversity_turn[int(np.sign(np.round(react[0], 1))) + 1] += 1 if food_positions.shape[0] > 0: all_dist = np.sqrt( np.sum((food_positions - f.pos)**2, axis=1)) closest_idx = np.argmin(all_dist) min_dist = all_dist[closest_idx] if (min_dist < 6): #print(min_dist) f.energy += 50 f.eaten += 1 dead_foods.append(foods.pop(closest_idx)) if len(foods) == 0: break food_positions = np.delete(food_positions, closest_idx, axis=0) #early stopping for bad individuals alive = len([f for f in fishes if f.energy > 0]) if alive <= 0 or len(foods) == 0: break #draw individuals for f in fishes: if f.energy > 0: f.draw(food_world) #res = merge_images_h([fish_world,food_world]) #subject to verbose if verbose: #print closest food ifdebug activated if debug and food_positions.shape[0] > 0: all_dist = np.sqrt( np.sum((food_positions - f.pos)**2, axis=1)) #for fp,d in zip(food_positions,all_dist): # print(fp,d,f.pos[::-1]) closest_idx = np.argmin(all_dist) min_dist = all_dist[closest_idx] fp = (int(food_positions[closest_idx][0]), int(food_positions[closest_idx][1])) cv2.circle(food_world, fp[::-1], 1, (0, 0, 255), 5) cv2.line(food_world, tuple(f.pos[::-1]), fp[::-1], (100, 30, 100), 1) res = np.minimum(fish_world, food_world) #print energy panel if energy: f_sorted = sorted(fishes, key=lambda f: f.energy, reverse=True) energies, colors = zip(*[('energy ' + str(round(f.energy, 2)), f.color) for f in f_sorted]) cb = command_bridge(f_size=0.7, commands=energies, colors=colors) res = merge_images_h([res, cb]) #print focused if verbose and food_focus: #find best food idx_best = np.argmax([f.lifetime for f in foods]) #select best food food_selected = foods[idx_best] #print squares for perception on the food_world+fishworld food_selected.print_perception(res) #get the focused area to show it focus_area = get_subwindow(res, pt=food_selected.pos[::-1], deltax=75, deltay=75) #draw a rectangle on it #cv2.rectangle(res,(int(food_selected.pos[1])-food_selected.s1, # int(food_selected.pos[0])-food_selected.s2), # (int(food_selected.pos[1])+food_selected.s1, # int(food_selected.pos[0])+food_selected.s2), # (244,0,0)) # plancia for the food cm_br = command_bridge( f_size=0.4, commands=[ 'Life Time ' + str(food_selected.lifetime), 'Pos ' + str(food_selected.pos), 'in' + str([round(e, 1) for e in food_selected.to_feed]), 'Out: turn ' + str(np.round(food_selected.outout[0], 2)) + 'Out: speed ' + str(np.round(food_selected.outout[1], 2)) ]) # mergeimages to show detail = merge_images_v(food_selected.percs + [focus_area, cm_br]) res = merge_images_h([res, detail]) if focus: if focus_best: idx_best = np.argmax([f.energy for f in fishes]) selected = fishes[idx_best] if selected.energy > 0: focus_area = get_subwindow(res, selected.pos[::-1], deltax=75, deltay=75) cm_br = command_bridge( f_size=0.4, commands=[ 'S ' + str(selected.speed), 'E ' + str(round(selected.energy, 1)), #'O '+str(round(selected.orient*180 / pi %360,0)) ] + ['in' + str([round(e, 1) for e in selected.to_feed])] + [ 'Out: turn ' + str(np.round(selected.outout[0], 2)) + ' Diversity ' + str(selected.diversity_turn), 'Out: speed ' + str(np.round(selected.outout[1], 2)) + ' Diversity ' + str(selected.diversity_speed), ]) selected.print_perception(res) detail = merge_images_v(selected.percs + [focus_area, cm_br]) res = merge_images_h([res, detail]) else: selected = None focus = False focus_best = focus for f in fishes: if f.energy > 0: f.move(food_world, dx=s1 - f.s1, dy=s2 - f.s2) #subject to verbose if verbose and not record: k = cv2.waitKey(33) # & 0xff print('keypressed', k) #81 left #82 up #84 down #83 right #32 space #100 d #101 e #27 esc if focus and selected != None: if k in [104, 107]: direct = -1 if k == 104 else 1 else: direct = 0 selected.turn(direction=direct) #for f in fishes: # if f!=selected: # f.turn(direction = rand.random()*2-1) if k == 98: if not focus_best: focus_best = True if not focus: focus = True else: focus = False focus_best = False #idx_best = np.argmax([f.energy for f in fishes]) #selected = fishes[idx_best] if k == 100: debug = not debug if k == 101: energy = not energy if k == 32: cv2.waitKey(0) #print('pressed',k) if k in [106, 108]: delta = -1 * (k - 107) print('increasing') if focus: selected.inc_speed(delta) else: for f in fishes: f.inc_speed(delta) if k == 27: if focus: focus = not focus focus_best = False else: break if verbose == 3: res = merge_images_v([ merge_images_h([ command_bridge(commands=(['Generation ' + str(epoch)])), command_bridge( commands=['Time left ' + str(max_time - time)]), command_bridge(commands=[ 'Avg speed ' + str(np.mean([f.speed for f in fishes if f.energy > 0])) ]), command_bridge(commands=(['Alive ' + str(alive)])) ]), res ]) if record: name = 'Generation_%03d' % epoch + '_time_%03d' % time + '.jpg' cv2.imwrite(folder + '/' + name, res) elif verbose: cv2.imshow('Simulation', res) '''if time ==0: paths = 255*np.zeros(food_world.shape) if time<300: for i in range(3): paths[:,:,i] += food_world[:,:,i]# np.minimum(food_world,food_world) cv2.imshow('path',merge_images_h([paths])) print(paths.shape)''' time += 1 '''if time %300 == 299: name = 'paths.jpg' paths = np.zeros(food_world.shape) break''' cv2.destroyAllWindows() if ALIVE: return num_foods, fishes, dead_foods + foods else: return num_foods, fishes