def test_next__preserves_the_beacon_oscillation(self): height = 6 width = 6 starting_cells = [(1,1), (1,2), (2,1), (2,2), (3,3), (3,4), (4,3), (4,4)] life = Life(starting_cells) next_board = life.next(width, height) expected_board = [ [0,0,0,0,0,0], [0,1,1,0,0,0], [0,1,0,0,0,0], [0,0,0,0,1,0], [0,0,0,1,1,0], [0,0,0,0,0,0]] self.assertEqual(next_board, expected_board, 'Beacon oscillation phase 1 not generated.') next_board = life.next(width, height) expected_board = [ [0,0,0,0,0,0], [0,1,1,0,0,0], [0,1,1,0,0,0], [0,0,0,1,1,0], [0,0,0,1,1,0], [0,0,0,0,0,0]] self.assertEqual(next_board, expected_board, 'Beacon oscillation phase 2 not generated.')
def test_next__one_live_cell_with_zero_live_neighbors_dies(self): starting_cells = [(1,1)] life = Life(starting_cells) next_board = life.next(self.width, self.height) self.assertEqual(next_board[1][1], 0, 'Board[1][1] was not dead.')
def test_next__returns_blank_board_if_all_starting_cells_dead(self): starting_cells = [] life = Life(starting_cells) next_board = life.next(self.width, self.height) self.assertEqual(next_board, self.expected_board, 'Next() did not return a blank board.')
def test_next__one_dead_cell_with_three_live_neighbors_lives(self): starting_cells = [(1,1), (1,2), (1,3)] life = Life(starting_cells) next_board = life.next(self.width, self.height) self.assertEqual(next_board[2][2], 1, 'Board[2][2] was not alive.')
class TerminalLifePanel(object): def __init__(self, seed): self.seed = seed self.game = Life() self.screen = curses.initscr() def main(self): self.screen.clear() self.draw_generation(self.seed) gen = self.game.next_gen(self.seed) while True: time.sleep(0.2) self.draw_generation(gen) gen = self.game.next_gen(gen) self.screen.refresh() self.screen.getch() curses.endwin() def draw_generation(self, data): self.screen.clear() for j, row in enumerate(data): for i, col in enumerate(row): if col: self.screen.addstr(j,i,'O') else: self.screen.addstr(j,i,' ') self.screen.refresh()
def test_next__called_twice_block_of_four_living_all_stay_alive(self): starting_cells = [(1,1), (1,2), (2,1), (2,2)] life = Life(starting_cells) next_board =life.next(self.width, self.height) next_board = life.next(self.width, self.height) self.assertEqual(next_board[1][1], 1, 'Board[1][1] was not alive.') self.assertEqual(next_board[1][2], 1, 'Board[1][2] was not alive.') self.assertEqual(next_board[2][1], 1, 'Board[2][1] was not alive.') self.assertEqual(next_board[2][2], 1, 'Board[2][2] was not alive.')
class GuiLifePanel(object): def __init__(self, seed): self.seed = seed self.current = None self.game = Life() self.top = Tkinter.Tk() self.top.protocol('WM_DELETE_WINDOW', self.window_closing) signal.signal(2, self.signal_closing) self.canvas = Tkinter.Canvas(self.top, bg='white', height=500, width=500) self.main() self.canvas.pack() self.top.mainloop() def window_closing(self): self.top.quit() def signal_closing(self, signum, frame): self.top.quit() def main(self): self.canvas.delete(Tkinter.ALL) if not self.current: self.draw_generation(self.seed) self.current= self.game.next_gen(self.seed) else: self.draw_generation(self.current) self.current = self.game.next_gen(self.current) self.top.after(100, self.main) def draw_generation(self, data): rec_size = 20 start_x = 10 start_y = 10 for j, row in enumerate(data): for i, col in enumerate(row): if col: self.canvas.create_rectangle( i*start_x, j*start_y, i*start_x+rec_size, j*start_y+rec_size, fill='black', width=0) else: self.canvas.create_rectangle( i*start_x, j*start_y, i*start_x+rec_size, j*start_y+rec_size, fill='white', width=0)
def show_lives(settings, screen, player, stats): """Draw text and ship images for lives.""" # Draw ship images. #remaining_lives.draw(screen) for number in range(stats.ships_left - 1): # Create life and add it to remaining_lives. new_life = Life(settings, screen, (settings.life_ship_offsetx + (settings.life_ship_spacing + 39) * number), settings.life_y) new_life.blitme() # Render number of lives into image and draw it. lives_text = Text(settings, screen, settings.font_size, str(stats.ships_left), settings.white, settings.life_text_offsetx, settings.life_y) lives_text.blitme()
def __init__(self, seed): self.seed = seed self.current = None self.game = Life() self.top = Tkinter.Tk() self.canvas = Tkinter.Canvas(self.top, bg='white', height=500, width=500) self.main() self.canvas.pack() self.top.mainloop()
def test_next__doesnt_break_on_negative_column_numbers(self): starting_cells = [(0,0), (1,0), (2,0)] life = Life(starting_cells) next_board = life.next(self.width, self.height) expected_board = [ [0,0,0,0,0], [1,1,0,0,0], [0,0,0,0,0], [0,0,0,0,0]] self.assertEqual(next_board, expected_board, 'negative numbers not handled correctly.') next_board = life.next(self.width, self.height) expected_board = [ [1,0,0,0,0], [1,0,0,0,0], [1,0,0,0,0], [0,0,0,0,0]] self.assertEqual(next_board, expected_board, 'negative numbers not handled correctly.')
def __init__(self, seed): self.seed = seed self.current = None self.game = Life() self.top = Tkinter.Tk() self.top.protocol('WM_DELETE_WINDOW', self.window_closing) signal.signal(2, self.signal_closing) self.canvas = Tkinter.Canvas(self.top, bg='white', height=500, width=500) self.main() self.canvas.pack() self.top.mainloop()
class TerminalLifePanel(object): def __init__(self, seed): self.seed = seed self.game = Life() self.screen = curses.initscr() self.running = True signal.signal(2, self.signal_closing) def signal_closing(self, signum, frame): self.running = False def main(self): self.screen.clear() self.draw_generation(self.seed) gen = self.game.next_gen(self.seed) while self.running: time.sleep(0.2) self.draw_generation(gen) gen = self.game.next_gen(gen) self.screen.refresh() curses.endwin() def draw_generation(self, data): self.screen.clear() for j, row in enumerate(data): for i, col in enumerate(row): if col: self.screen.addstr(j,i,'O') else: self.screen.addstr(j,i,' ') self.screen.refresh()
def test_life(self): l = Life() l.start(1, 0) for sublist in l.life_grid: for element in sublist: self.assertFalse(element) for i in xrange(2, 11): l.start(1, 0) for sublist in l.life_grid: for element in sublist: self.assertFalse(element) for i in xrange(10): l.start(10, 0) for sublist in l.life_grid: for element in sublist: self.assertFalse(element)
def __init__(self, x, y): self.sun = randint(0, 99) self.sun_cap = 100 + randint(0, 100) self.death_counter = 0 self.death_cap = 200 Life.__init__(self, x, y)
class Environment: def __init__(self, rounds_per_episode=8, display=False): self.life = Life(display=display) self.rows = self.life.rows self.cols = self.life.cols self.color = 'blue' self.rounds_per_episode = rounds_per_episode self.moves_per_round = 3 # TODO clean variable name like this in two_player # Inputs and outputs for our models self.x1_shape = (self.rows, self.cols, 3) # board state self.x2_shape = (self.moves_per_round,) # move tile counter self.x3_shape = (self.rounds_per_episode,) # round counter self.model_board_shape = (self.rows, self.cols*2, 3) # concatenated boards shape self.y_shape = (self.rows*self.cols + 1,) # actions, one additional for "passing" self.reset() def reset(self): # these variables are reset every episode self.episode_round_n = 0 self.episode_action_n = 0 self.move_tile_counter = 0 self.first_move = True max_per_ep = self.rounds_per_episode*self.moves_per_round self.board_states = np.zeros((max_per_ep,) + self.x1_shape, dtype='bool') self.move_tile_counters = np.zeros((max_per_ep,) + self.x2_shape, dtype='bool') self.round_counters = np.zeros((max_per_ep,) + self.x3_shape, dtype='bool') self.actions = np.zeros((max_per_ep,) + self.y_shape, dtype='bool') self.final_board = np.zeros(self.x1_shape, dtype='bool') self.life.clean() def encode_action(self, cell): action = np.zeros(self.y_shape, dtype='bool') if cell == None: action[self.cols*self.rows] = 1 else: i, j = cell action[i*self.cols + j] = 1 return action def decode_action(self, action): if action == self.rows*self.cols: return None else: row, col = (action // self.cols, action % self.cols) return (row, col) def board_state(self): # 3 possible cell states blank = np.array([1, 0, 0], dtype='bool') alive = np.array([0, 1, 0], dtype='bool') dead = np.array([0, 0, 1], dtype='bool') encoded_board = np.zeros(self.x1_shape, dtype='bool') for i in range(self.life.rows): for j in range(self.life.cols): v = self.life.get_cell_value((i, j)) if v == self.life.BLANK: encoded_board[i][j] = blank elif v == self.life.LIVE_BLUE: encoded_board[i][j] = alive elif v == self.life.DEAD_BLUE: encoded_board[i][j] = dead return encoded_board def state(self): """ Returns (board_state, move_tile_counter, round_counter)""" move_tile_counter_i_mat = np.identity(self.moves_per_round, dtype='bool') encoded_move_tile_counter = move_tile_counter_i_mat[self.move_tile_counter] # encoded round_number, which tells you how many rounds have occured this episode round_identity_matrix = np.identity(self.rounds_per_episode, dtype='bool') encoded_round_counter = round_identity_matrix[self.episode_round_n] return (self.board_state(), encoded_move_tile_counter, encoded_round_counter) def step(self, action): cell = self.decode_action(action) if self.is_legal_move(cell): # for replay experience self.memorize_state() self.memorize_action(cell) if cell != None: # cell being None would mean the agent "passed" self.life.accept_tiles([cell], self.color) self.first_move = False self.move_tile_counter += 1 self.episode_action_n += 1 if self.move_tile_counter == self.moves_per_round: self.life.advance_state() self.move_tile_counter = 0 self.episode_round_n += 1 return def is_done(self): if self.episode_round_n == self.rounds_per_episode: self.memorize_final_board() return True if self.life.count_live_total() == 0 and self.first_move == False: self.memorize_final_board() return True return False def is_legal_move(self, cell): """ On the first tile placement on the first round of an episode, the tile can be legally placed anywhere. After that, the a legal tile placement must neighbor a live tile. """ if cell == None: return True if is_live(self.life.get_cell_value(cell)): return False if self.first_move: return True elif self.life.count_live_neighbors(cell) == 0: return False return True def legal_move_mask(self): legal_move_mask = np.zeros((self.rows, self.cols), dtype='bool') for i in range(self.rows): for j in range(self.cols): legal_move_mask[i][j] = self.is_legal_move((i, j)) flattened = np.ravel(legal_move_mask) return np.append(flattened, np.array([1])) def memorize_final_board(self): encoded_final_board = self.board_state() self.final_board = encoded_final_board def memorize_action(self, cell): i = self.episode_action_n self.actions[i] = self.encode_action(cell) def memorize_state(self): i = self.episode_action_n encoded_board, encoded_move_tile_counter, encoded_round_counter = self.state() self.board_states[i] = encoded_board self.move_tile_counters[i] = encoded_move_tile_counter self.round_counters[i] = encoded_round_counter def get_episode_memories(self): # put the actual and final board states as a single 'image' final_board_expanded = np.array([self.final_board]*len(self.board_states), dtype='bool') board_states = np.concatenate((self.board_states, final_board_expanded), axis=2) # remove initial padding n = self.episode_action_n board_states = board_states[:n] move_tile_counters = self.move_tile_counters[:n] round_counters = self.round_counters[:n] actions = self.actions[:n] return (board_states, move_tile_counters, round_counters, actions)
def test_next__returns_blank_board_of_requested_dimensions_if_no_starting_items(self): life = Life() next_board = life.next(self.width, self.height) self.assertEqual(next_board, self.expected_board, 'Next() did not return a blank board.')
r_coords = [(25, 37), (25, 38), (26, 36), (26, 37), (27, 37)] for cell in r_coords: r_seed.set(cell[0], cell[1], LIVE) # Pulsar pulsar_seed = Grid(30, 50) pulsar_coords = [(1, 5), (1, 11), (2, 5), (2, 11), (3, 5), (3, 6), (3, 10), (3, 11), (5, 1), (5, 2), (5, 3), (5, 6), (5, 7), (5, 9), (5, 10), (5, 13), (5, 14), (5, 15), (6, 3), (6, 5), (6, 7), (6, 9), (6, 11), (6, 13), (7, 5), (7, 6), (7, 10), (7, 11), (9, 5), (9, 6), (9, 10), (9, 11), (10, 3), (10, 5), (10, 7), (10, 9), (10, 11), (10, 13), (11, 1), (11, 2), (11, 3), (11, 6), (11, 7), (11, 9), (11, 10), (11, 13), (11, 14), (11, 15), (13, 5), (13, 6), (13, 10), (13, 11), (14, 5), (14, 11), (15, 5), (15, 11)] for cell in pulsar_coords: pulsar_seed.set(cell[0], cell[1], LIVE) game = Life(pulsar_seed) counter = 0 while True: print game print "Counter: ", counter time.sleep(.1) game.tick() counter += 1
def ready(self): monome.Page.ready(self) Life.ready(self)
class SpaceInvaders(object): def __init__(self): pygame.mixer.pre_init(44100, -16, 1, 4096) pygame.init() self.clock = pygame.time.Clock() self.caption = pygame.display.set_caption('Space Invaders') self.screen = sett.SCREEN self.background = pygame.image.load(sett.IMAGE_PATH + 'space_bg.jpg').convert() self.startGame = False self.mainScreen = True self.gameOver = False #BUTTONS self.play_button = ButtonPlay(self.screen, "PLAY") self.hs_button = ButtonHighScores(self.screen, "HIGH SCORES") self.mouse_x, self.mouse_y = pygame.mouse.get_pos() self.play_button_clicked = self.play_button.rect.collidepoint( self.mouse_x, self.mouse_y) self.hs_button_clicked = self.hs_button.rect.collidepoint( self.mouse_x, self.mouse_y) # Counter for enemy starting position (increased each new round) self.enemyPosition = sett.ENEMY_DEFAULT_POSITION self.titleText = Text(sett.FONT, 80, 'SPACE INVADERS', sett.GREEN, 15, 50) #TEXT self.gameOverText = Text(sett.FONT, 50, 'Game Over', sett.WHITE, 250, 270) self.nextRoundText = Text(sett.FONT, 50, 'Next Round', sett.WHITE, 240, 270) self.enemy1Text = Text(sett.FONT, 25, ' = 10 pts', sett.GREEN, 368, 270) self.enemy2Text = Text(sett.FONT, 25, ' = 20 pts', sett.BLUE, 368, 320) self.enemy3Text = Text(sett.FONT, 25, ' = 30 pts', sett.PURPLE, 368, 370) self.enemy4Text = Text(sett.FONT, 25, ' = ?????', sett.RED, 368, 420) self.scoreText = Text(sett.FONT, 20, 'Score', sett.WHITE, 5, 5) self.livesText = Text(sett.FONT, 20, 'Lives ', sett.WHITE, 640, 5) #PLAYER LIVES self.life1 = Life(715, 3) self.life2 = Life(742, 3) self.life3 = Life(769, 3) self.livesGroup = pygame.sprite.Group(self.life1, self.life2, self.life3) def reset(self, score): self.player = Ship() self.player_group = pygame.sprite.Group(self.player) self.explosions_group = pygame.sprite.Group() self.bullets = pygame.sprite.Group() self.mystery_ship = Mystery() self.mystery_group = pygame.sprite.Group(self.mystery_ship) self.enemy_bullets = pygame.sprite.Group() self.make_enemies() self.all_sprites = pygame.sprite.Group(self.player, self.enemies, self.livesGroup, self.mystery_ship) self.keys = pygame.key.get_pressed() self.timer = pygame.time.get_ticks() self.note_timer = pygame.time.get_ticks() self.ship_timer = pygame.time.get_ticks() self.score = score self.create_audio() self.make_new_ship = False self.ship_alive = True def make_blockers(self, number): blockerGroup = pygame.sprite.Group() for row in range(4): for column in range(9): blocker = Blocker(10, sett.GREEN, row, column) blocker.rect.x = 50 + (200 * number) + (column * blocker.width) blocker.rect.y = sett.BLOCKERS_POSITION + (row * blocker.height) blockerGroup.add(blocker) return blockerGroup def create_audio(self): self.sounds = {} for sound_name in [ 'shoot', 'shoot2', 'invaderkilled', 'mysterykilled', 'shipexplosion', 'si_background' ]: self.sounds[sound_name] = pygame.mixer.Sound( sett.SOUND_PATH + '{}.wav'.format(sound_name)) self.sounds[sound_name].set_volume(0.2) self.musicNotes = [ pygame.mixer.Sound(sett.SOUND_PATH + '{}.wav'.format(i)) for i in range(4) ] for sound in self.musicNotes: sound.set_volume(0.5) self.noteIndex = 0 def play_main_music(self, current_time): if current_time - self.note_timer > self.enemies.moveTime: self.note = self.musicNotes[self.noteIndex] if self.noteIndex < 3: self.noteIndex += 1 else: self.noteIndex = 0 self.note.play() self.note_timer += self.enemies.moveTime @staticmethod def should_exit(evt): # type: (pygame.event.EventType) -> bool return evt.type == pygame.QUIT or (evt.type == pygame.KEYUP and evt.key == pygame.K_ESCAPE) def check_input(self): self.keys = pygame.key.get_pressed() for e in pygame.event.get(): if self.should_exit(e): sys.exit() if e.type == pygame.KEYDOWN: if e.key == pygame.K_SPACE: if len(self.bullets) == 0 and self.ship_alive: if self.score < 1000: bullet = Bullet(self.player.rect.x + 23, self.player.rect.y + 5, -1, 15, 'laser', 'center') self.bullets.add(bullet) self.all_sprites.add(self.bullets) self.sounds['shoot'].play() else: left_bullet = Bullet(self.player.rect.x + 8, self.player.rect.y + 5, -1, 15, 'laser', 'left') right_bullet = Bullet(self.player.rect.x + 38, self.player.rect.y + 5, -1, 15, 'laser', 'right') self.bullets.add(left_bullet) self.bullets.add(right_bullet) self.all_sprites.add(self.bullets) self.sounds['shoot2'].play() def make_enemies(self): enemies = EnemiesGroup(10, 5) for row in range(5): for column in range(10): enemy = Enemy(row, column) enemy.rect.x = 157 + (column * 50) enemy.rect.y = self.enemyPosition + (row * 45) enemies.add(enemy) self.enemies = enemies def make_enemies_shoot(self): if (pygame.time.get_ticks() - self.timer) > 700 and self.enemies: enemy = self.enemies.random_bottom() self.enemy_bullets.add( Bullet(enemy.rect.x + 14, enemy.rect.y + 20, 1, 5, 'enemylaser', 'center')) self.all_sprites.add(self.enemy_bullets) self.timer = pygame.time.get_ticks() def calculate_score(self, row): scores = { 0: 30, 1: 20, 2: 20, 3: 10, 4: 10, 5: choice([50, 100, 150, 300]) } score = scores[row] self.score += score return score def create_main_menu(self): self.enemy1 = sett.IMAGES['enemy3_1'] self.enemy1 = pygame.transform.scale(self.enemy1, (40, 40)) self.enemy2 = sett.IMAGES['enemy2_2'] self.enemy2 = pygame.transform.scale(self.enemy2, (40, 40)) self.enemy3 = sett.IMAGES['enemy1_2'] self.enemy3 = pygame.transform.scale(self.enemy3, (40, 40)) self.enemy4 = sett.IMAGES['mystery'] self.enemy4 = pygame.transform.scale(self.enemy4, (80, 40)) self.screen.blit(self.enemy1, (318, 270)) self.screen.blit(self.enemy2, (318, 320)) self.screen.blit(self.enemy3, (318, 370)) self.screen.blit(self.enemy4, (299, 420)) if not self.startGame: self.play_button.draw_button() self.hs_button.draw_button() def check_collisions(self): pygame.sprite.groupcollide(self.bullets, self.enemy_bullets, True, True) #When an alien is hit for enemy in pygame.sprite.groupcollide(self.enemies, self.bullets, True, True).keys(): self.sounds['invaderkilled'].play() self.calculate_score(enemy.row) EnemyExplosion(enemy, self.explosions_group) self.game_timer = pygame.time.get_ticks() #When mystery is hit for mystery in pygame.sprite.groupcollide(self.mystery_group, self.bullets, True, True).keys(): mystery.mysteryEntered.stop() self.sounds['mysterykilled'].play() score = self.calculate_score(mystery.row) MysteryExplosion(mystery, score, self.explosions_group) new_ship = Mystery() self.all_sprites.add(new_ship) self.mystery_group.add(new_ship) #When player is hit for player in pygame.sprite.groupcollide(self.player_group, self.enemy_bullets, True, True).keys(): if self.life3.alive(): self.life3.kill() elif self.life2.alive(): self.life2.kill() elif self.life1.alive(): self.life1.kill() else: self.gameOver = True self.startGame = False self.sounds['shipexplosion'].play() ShipExplosion(player, self.explosions_group) self.make_new_ship = True self.ship_timer = pygame.time.get_ticks() self.ship_alive = False if self.enemies.bottom >= 540: pygame.sprite.groupcollide(self.enemies, self.player_group, True, True) if not self.player.alive() or self.enemies.bottom >= 600: self.gameOver = True self.startGame = False pygame.sprite.groupcollide(self.bullets, self.all_blockers, True, True) pygame.sprite.groupcollide(self.enemy_bullets, self.all_blockers, True, True) if self.enemies.bottom >= sett.BLOCKERS_POSITION: pygame.sprite.groupcollide(self.enemies, self.all_blockers, False, True) def create_new_ship(self, create_ship, current_time): if create_ship and (current_time - self.ship_timer > 900): self.player = Ship() self.all_sprites.add(self.player) self.player_group.add(self.player) self.make_new_ship = False self.ship_alive = True def create_game_over(self, current_time): self.screen.blit(self.background, (0, 0)) passed = current_time - self.timer if passed < 750: self.gameOverText.draw(self.screen) elif 750 < passed < 1500: self.screen.blit(self.background, (0, 0)) elif 1500 < passed < 2250: self.gameOverText.draw(self.screen) elif 2250 < passed < 2750: self.screen.blit(self.background, (0, 0)) elif passed > 3000: self.mainScreen = True for e in pygame.event.get(): if self.should_exit(e): sys.exit() #Main game function def main(self): while True: if self.mainScreen: self.screen.blit(self.background, (0, 0)) self.titleText.draw(self.screen) self.enemy1Text.draw(self.screen) self.enemy2Text.draw(self.screen) self.enemy3Text.draw(self.screen) self.enemy4Text.draw(self.screen) self.create_main_menu() for e in pygame.event.get(): if self.should_exit(e): sys.exit() #When play button is pressed if e.type == pygame.MOUSEBUTTONDOWN: self.mouse_x, self.mouse_y = pygame.mouse.get_pos() self.play_button_clicked = self.play_button.rect.collidepoint( self.mouse_x, self.mouse_y) self.hs_button_clicked = self.play_button.rect.collidepoint( self.mouse_x, self.mouse_y) if self.play_button_clicked and not self.startGame: bg_music = pygame.mixer.Sound(sett.SOUND_PATH + 'si_background.wav') bg_music.set_volume(0.5) bg_music.play() # Only create blockers on a new game, not a new round self.all_blockers = pygame.sprite.Group( self.make_blockers(0), self.make_blockers(1), self.make_blockers(2), self.make_blockers(3)) self.livesGroup.add(self.life1, self.life2, self.life3) self.reset(0) self.startGame = True self.mainScreen = False #When high scores button is pressed if self.hs_button_clicked and not self.startGame: file_contents = [] #List to store file contents with open('high_score.txt', 'r') as f: file_contents = f.readlines() file_contents = str( file_contents) #converts everything to strings remove_char = ["'", "\\n", ",", "[", "]"] for char in remove_char: file_contents = file_contents.replace(char, "") pygame.font.init() text_color = sett.WHITE display_surface = pygame.display.set_mode( sett.screen_width, sett.screen_height, 0, 32) pygame.display.set_caption('HIGH SCORES') font_1 = pygame.font.Font('freesansbold.ttf', 16) text_1 = font_1.render(str(file_contents), True, text_color) text_rect = text_1.get_rect() text_rect.center = (sett.screen_width // 2, sett.screen_height // 2) while True: #Check for the QUIT event. # completely fill the surface object # with white color display_surface.blit(self.background, (0, 0)) # display.update() self.highScoreText.draw(self.screen) display_surface.blit(text_1, text_rect) pygame.display.update() pygame.time.sleep(5) # copying the text surface object # to the display surface object # at the center coordinate. # deactivates the pygame library sys.exit() elif self.startGame: if not self.enemies and not self.explosions_group: current_time = pygame.time.get_ticks() if current_time - self.game_timer < 3000: self.screen.blit(self.background, (0, 0)) self.score_text2 = Text(sett.FONT, 20, str(self.score), sett.GREEN, 85, 5) self.scoreText.draw(self.screen) self.score_text2.draw(self.screen) self.nextRoundText.draw(self.screen) self.livesText.draw(self.screen) self.livesGroup.update() self.check_input() if current_time - self.game_timer > 3000: # Move enemies closer to bottom self.enemyPosition += sett.ENEMY_MOVE_DOWN self.reset(self.score) self.game_timer += 3000 else: current_time = pygame.time.get_ticks() self.play_main_music(current_time) self.screen.blit(self.background, (0, 0)) self.all_blockers.update(self.screen) self.score_text2 = Text(sett.FONT, 20, str(self.score), sett.GREEN, 85, 5) self.scoreText.draw(self.screen) self.score_text2.draw(self.screen) self.livesText.draw(self.screen) self.check_input() self.enemies.update(current_time) self.all_sprites.update(self.keys, current_time) self.explosions_group.update(current_time) self.check_collisions() self.create_new_ship(self.make_new_ship, current_time) self.make_enemies_shoot() elif self.gameOver: current_time = pygame.time.get_ticks() # Reset enemy starting position self.enemyPosition = sett.ENEMY_DEFAULT_POSITION self.create_game_over(current_time) pygame.display.update() self.clock.tick(60)
self.app1 = app1 self.app2 = app2 async def pages_connect(self, port): transport, grid = await self.loop.create_datagram_endpoint(monome.Grid, local_addr=('127.0.0.1', 0), remote_addr=('127.0.0.1', port)) page1 = monome.Page() page2 = monome.Page() page_manager = monome.SeqPageManager(grid=grid, pages=[page1, page2]) self.app1.attach(page1) self.app2.attach(page2) page_manager.connect() def on_device_added(self, id, type, port): asyncio.async(self.pages_connect(port)) if __name__ == "__main__": life1 = Life() life2 = Life() loop = asyncio.get_event_loop() asyncio.async(PagesSerialOsc.create(loop=loop, app1=life1, app2=life2)) try: loop.run_forever() except KeyboardInterrupt: life1.quit() life2.quit()
from life import Life from patterns import gun p = Life() p.add(gun) for i in range(1, 46): p.export("output/gun-frame" + str(i) + ".png", ) p.next()
def __init__(self, x, y): self.death_counter = 0 self.death_cap = 350 Life.__init__(self, x, y)
import sys import time from ast import literal_eval filename = sys.argv[1] if len(sys.argv) >= 2 else 'beacon.txt' width = int(sys.argv[2]) if len(sys.argv) >= 3 else 6 height = int(sys.argv[3]) if len(sys.argv) >= 4 else 6 speed = int(sys.argv[4]) if len(sys.argv) >= 5 else 4 starting_cells = [] with open(filename, 'r') as in_file: for line in in_file.readlines(): if line[0] == '(': starting_cells.append(literal_eval(line)) life = Life(starting_cells) live_char = '+' if os.name == 'nt': clear_command = 'cls' else: clear_command = 'clear' for x in range(1000): os.system(clear_command) board = life.next(width, height) for row in board: for col in row: if col: print(live_char, end='') else:
if __name__ == '__main__': # subjects ranges family_range = 3 friends_range = 10 coworkers_range = 50 others_range = 10 # simulation start time now = datetime.datetime.now(datetime.timezone.utc) year = now.year month = 5 day = 4 hour = 7 d = datetime.datetime(now.year, month, day, hour, 0, 0) ts = datetime2utc_time(d) print("start time:", ts, datetime.datetime.utcfromtimestamp(ts).isoformat()) life = Life(ts, family_range, friends_range, coworkers_range, others_range) # start simulation life.start() # generate report and download report = life.generate_report() report = json.loads(report) print(report)
class Game: def __init__(self): self.life = Life() self.reset() def reset(self): self.life.clean() self.turn = 'red' self.move_tile_counter = 0 self.tiles_per_move = 3 self.first_red_move = True self.first_blue_move = True def is_done(self): """ There are two conditions for a completed game. 1. All tiles are colored 2. A color has no live tiles """ blank_count = 0 live_red_count = 0 live_blue_count = 0 for i in range(self.life.rows): for j in range(self.life.cols): cell = self.life.get_cell_value((i, j)) if cell == BLANK: blank_count += 1 elif cell == LIVE_RED: live_red_count += 1 elif cell == LIVE_BLUE: live_blue_count += 1 if blank_count == 0 or live_red_count == 0 or live_blue_count == 0: if not self.first_red_move and not self.first_blue_move: return True return False def score(self): red = 0 blue = 0 for i in range(self.life.rows): for j in range(self.life.cols): cell = self.life.get_cell_value((i, j)) if cell == LIVE_RED or cell == DEAD_RED: red += 1 elif cell == LIVE_BLUE or cell == DEAD_BLUE: blue += 1 return red, blue def winner(self): red, blue = self.score() if red > blue: return 'red' else: return 'blue' def accept_move(self, cell): if self.is_legal_move(cell, self.turn, debug=True): self.life.accept_tiles([cell], self.turn) self.move_tile_counter += 1 if self.turn == 'red': self.first_red_move = False else: self.first_blue_move = False if self.move_tile_counter == self.tiles_per_move: if self.turn == 'red': self.turn = 'blue' else: self.turn = 'red' self.life.advance_state() self.move_tile_counter = 0 return True return False def is_legal_move(self, cell, player, debug=False): """ All moves must be made on dead or blank tiles. Your first tile can be placed anywhere as long as it doesn't border an opponent's live tile. After that, a legal move is one in which your chosen tile is a neighbor of a live tile you control. """ if is_live(self.life.get_cell_value(cell)): if debug: print(f'{self.turn}, {cell}, attempted placement on live tile') return False red_neighbors, blue_neighbors = self.life.neighbors(cell) if player == 'red': ally_neighbors = red_neighbors opponent_neighbors = blue_neighbors else: ally_neighbors = blue_neighbors opponent_neighbors = red_neighbors if (self.first_red_move and player == 'red') or (self.first_blue_move and player == 'blue'): if opponent_neighbors > 0: if debug: print( f'{self.turn}, {cell}, attempted placement next to opponent on first move' ) return False return True else: if ally_neighbors > 0: return True if debug: print( f'{self.turn}, {cell}, attempted placement away from ally on non-starting move' ) return False def encoded(self): player = self.turn # 5 possible cell states blank = np.array([1, 0, 0, 0, 0], dtype='bool') ally_alive = np.array([0, 1, 0, 0, 0], dtype='bool') ally_dead = np.array([0, 0, 1, 0, 0], dtype='bool') enemy_alive = np.array([0, 0, 0, 1, 0], dtype='bool') enemy_dead = np.array([0, 0, 0, 0, 1], dtype='bool') encoded_board = np.zeros((self.life.rows, self.life.cols, 5), dtype='bool') for i in range(self.life.rows): for j in range(self.life.cols): if self.life.get_cell_value((i, j)) == BLANK: encoded_board[i][j] = blank elif self.life.get_cell_value((i, j)) == LIVE_RED: if player == 'red': encoded_board[i][j] = ally_alive else: encoded_board[i][j] = enemy_alive elif self.life.get_cell_value((i, j)) == LIVE_BLUE: if player == 'blue': encoded_board[i][j] = ally_alive else: encoded_board[i][j] = enemy_alive elif self.life.get_cell_value((i, j)) == DEAD_RED: if player == 'red': encoded_board[i][j] = ally_dead else: encoded_board[i][j] = enemy_dead elif self.life.get_cell_value((i, j)) == DEAD_BLUE: if player == 'blue': encoded_board[i][j] = ally_dead else: encoded_board[i][j] = enemy_dead move_tile_count_1 = np.array([1, 0, 0], dtype='bool') move_tile_count_2 = np.array([0, 1, 0], dtype='bool') move_tile_count_3 = np.array([0, 0, 1], dtype='bool') if self.move_tile_counter == 0: encoded_move_tile_count = move_tile_count_1 elif self.move_tile_counter == 1: encoded_move_tile_count = move_tile_count_2 else: encoded_move_tile_count = move_tile_count_3 return (encoded_board, encoded_move_tile_count)
class Environment: def __init__(self, rounds_per_episode=16, display=False): self.life = Life(display=display) self.rows = self.life.rows self.cols = self.life.cols self.color = 'blue' self.rounds_per_episode = rounds_per_episode self.moves_per_round = 3 # TODO clean variable name like this in two_player # Inputs and outputs for our models self.x1_shape = (self.rows, self.cols, 3) # board state self.x2_shape = (self.moves_per_round, ) # move tile counter self.x3_shape = (self.rounds_per_episode + 1, ) # round counter self.y_shape = (self.rows * self.cols + 1, ) # actions, one additional for "passing" self.nb_actions = self.rows * self.cols + 1 self.reset() def reset(self): # these variables are reset every episode self.episode_round_n = 0 self.episode_action_n = 0 self.move_tile_counter = 0 self.first_move = True self.life.clean() return self.state() def encode_action(self, cell): action = np.zeros(self.y_shape, dtype='bool') if cell == None: action[self.cols * self.rows] = 1 else: i, j = cell action[i * self.cols + j] = 1 return action def decode_action(self, action): legal_move_mask = self.legal_move_mask() if legal_move_mask[action] == 0: # move is illegal return None # illegal move means pass if action == self.rows * self.cols: return None else: row, col = (action // self.cols, action % self.cols) return (row, col) def encode_board(self): """ Returns encoded board state with shape (rows, cols, 3,) """ # 3 possible cell states blank = np.array([1, 0, 0], dtype='bool') alive = np.array([0, 1, 0], dtype='bool') dead = np.array([0, 0, 1], dtype='bool') encoded_board = np.zeros(self.x1_shape, dtype='bool') for i in range(self.life.rows): for j in range(self.life.cols): v = self.life.get_cell_value((i, j)) if v == self.life.BLANK: encoded_board[i][j] = blank elif v == self.life.LIVE_BLUE: encoded_board[i][j] = alive elif v == self.life.DEAD_BLUE: encoded_board[i][j] = dead return encoded_board def encode_move_tile_counter(self): """ Returns encoded form of how many moves have occured this round """ move_tile_counter_i_mat = np.identity(self.moves_per_round, dtype='bool') encoded_move_tile_counter = move_tile_counter_i_mat[ self.move_tile_counter] return encoded_move_tile_counter def encode_round_counter(self): """ Returns encoded form of how many rounds have occured this episode """ round_identity_matrix = np.identity(self.rounds_per_episode + 1, dtype='bool') encoded_round_counter = round_identity_matrix[self.episode_round_n] return encoded_round_counter def state(self): """ Returns [board_state, move_tile_counter, round_counter]""" return self.encode_board(), self.encode_move_tile_counter( ), self.encode_round_counter() def step(self, action): cell = self.decode_action(action) if cell != None: # cell being None would mean the agent "passed" self.life.accept_tiles([cell], self.color) self.first_move = False self.move_tile_counter += 1 self.episode_action_n += 1 if self.move_tile_counter == self.moves_per_round: self.life.advance_state() self.move_tile_counter = 0 self.episode_round_n += 1 state = self.state() done = self.is_done() if done: reward = self.life.count_colored() else: reward = 0 return (state, reward, done, {}) def is_done(self): if self.episode_round_n == self.rounds_per_episode: return True if self.life.count_live_total() == 0 and self.first_move == False: return True return False def is_legal_move(self, cell): """ On the first tile placement on the first round of an episode, the tile can be legally placed anywhere. After that, the a legal tile placement must neighbor a live tile. """ if cell == None: return True if is_live(self.life.get_cell_value(cell)): return False if self.first_move: return True elif self.life.count_live_neighbors(cell) == 0: return False return True def legal_move_mask(self): legal_move_mask = np.zeros((self.rows, self.cols), dtype='bool') for i in range(self.rows): for j in range(self.cols): legal_move_mask[i][j] = self.is_legal_move((i, j)) flattened = np.ravel(legal_move_mask) return np.append(flattened, np.array([1]))
class HeroPlane: t = 0 def __init__(self, screen): self.x = 230 self.y = 500 self.screen = screen self.image_name = "./feiji/hero.gif" self.image_name1 = "./feiji/hero1.gif" self.image = pygame.image.load(self.image_name).convert() self.image1 = pygame.image.load(self.image_name1).convert() self.t = 0 self.bullet_list = [] self.bload = [] for i in range(70): self.bload.append([]) self.life = Life(screen) for i in range(70): for j in range(76): self.bload[i].append(False) self.block() def is_hurt(self, bad_bullet_list): for bad_bullet in bad_bullet_list: if bad_bullet.x - self.x < 0 or bad_bullet.x - self.x > 69 or bad_bullet.y - self.y < 0 or bad_bullet.y - self.y >75: continue if self.bload[bad_bullet.x - self.x][bad_bullet.y - self.y]: if not self.life.hurt(): return bad_bullet else: return "game over" return None # 简单把飞机分成3块,以飞机的x, y为参照点,这3个范围可以被击中。 # (32, 0)->(37, 17) # (0, 25)->(70, 46) # (20, 46)->(52, 63) def block(self): for i in range(32, 37): for j in range(0, 17): self.bload[i][j] = True for i in range(0, 70): for j in range(25, 46): self.bload[i][j] = True for i in range(20, 52): for j in range(46, 63): self.bload[i][j] = True def boundary_x(self): if self.x < -70: self.x = 400 elif self.x > 400: self.x = -70 def boundary_y(self): if self.y < 0: self.y = 0 if self.y > 624: self.y = 624 def launch_bullet(self): new_bullet = Bullet(self.x, self.y, self.screen) self.bullet_list.append(new_bullet) def display(self): if HeroPlane.t % 10 < 5: self.screen.blit(self.image, (self.x, self.y)) else: self.screen.blit(self.image1, (self.x, self.y)) HeroPlane.t += 1 if HeroPlane.t > 1000000: HeroPlane.t -= 1000000 need_del_list = [] for item in self.bullet_list: if item.judge(): need_del_list.append(item) for def_item in need_del_list: self.bullet_list.remove(def_item) for bullet in self.bullet_list: bullet.display() bullet.move() self.life.display() def move_left(self): self.x -= 20 self.boundary_x() def move_right(self): self.x += 20 self.boundary_x() def move_up(self): self.y -= 20 self.boundary_y() def move_down(self): self.y += 20 self.boundary_y()
__author__ = 'Serban Carlogea' __email__ = '*****@*****.**' from life import Life if __name__ == "__main__": Life().run()
self.app1.attach(page1) self.app2.attach(page2) page_manager.connect() def on_device_added(self, id, type, port): asyncio. async (self.pages_connect(port)) if __name__ == '__main__': loop = asyncio.get_event_loop() pages = monome.SumGridPageManager(2) life1 = Life() life1.set_grid(pages.pages[0]) life2 = Life() life2.set_grid(pages.pages[1]) def serialosc_device_added(id, type, port): print('connecting to {} ({})'.format(id, type)) asyncio.ensure_future(pages.grid.connect('127.0.0.1', port)) serialosc = monome.SerialOsc() serialosc.device_added_event.add_handler(serialosc_device_added) loop.run_until_complete(serialosc.connect()) loop.run_forever()
def create_life(screen, setting, lifes): for i in range(setting.ship_limit): life = Life(screen) life.rect.centerx = life.rect.width * (i + 1) life.rect.centery = 20 lifes.add(life)
def __init__(self, seed): self.seed = seed self.game = Life() self.screen = curses.initscr() self.running = True signal.signal(2, self.signal_closing)
from __future__ import print_function from graphics import * from life import Life import time life = Life(6, 6) life.set_cell(1, True) life.set_cell(2, True) life.set_cell(3, True) def show_grid(): grid = life.get_grid() gx, gy = life.get_grid_dim() for i in range(len(grid)): print(grid[i], end='') if i % gx == gx - 1: print("") # iter = 0 # while True: # print("Iteration {} Population {}".format(iter, life.get_population())) # show_grid() # x = raw_input("Enter to continue") # life.process_life() # iter += 1 win = GraphWin(width=400, height=400) # create a window
def __init__(self, app): monome.Page.__init__(self, app) Life.__init__(self)
def main_window(speed, difficulty): # 기본 설정들 word = Word('E') # 단어 생성 모듈 width, height = 640, 480 screen = pygame.display.set_mode((width, height)) pygame.display.set_caption("Mole Game") screen.fill(GREEN) running = True wordsLst = [] mainTimer = 80 - speed # 단어 생성 시간 # 이미지 좌표들 heart_rect_lst = [(600, 10), (560, 10), (520, 10), (480, 10), (440, 10), (400, 10), (360, 10)] word_rect_lst = [[50, 150], [50, 250], [50, 350], [230, 150], [230, 250], [230, 350], [410, 150], [410, 250], [410, 350]] answer = "" score = Score() # 점수 관리 모듈 scoreTxt = 'score: ' + str(score.getScore()) life = Life(difficulty) # 목숨 관리 모듈 heartLst = [[heartimg, heart_rect_lst[i]] for i in range(life.getLife())] # 게임 시작 while running: screen.fill(GREEN) # 텍스트박스 출력 screen.blit(textBox.image, textBox.rect) scoreTxt = 'score: ' + str(score.getScore()) scoreSurface = fontObj.render(scoreTxt, True, BLACK) screen.blit(scoreSurface, (10, 10)) # 책 출력 for i in range(9): screen.blit(dictimg, (word_rect_lst[i][0] + 40, word_rect_lst[i][1] - 50)) # 목숨 수 출력 for i in range(len(heartLst)): screen.blit(heartLst[i][0], heartLst[i][1]) # 단어 생성 if mainTimer <= 0: speed += 0.5 wordRan = word.randFromDB(difficulty) textSurface = fontObj.render( wordRan, True, BLACK ) # 텍스트 객체를 생성한다. 첫번째 파라미터는 텍스트 내용, 두번째는 Anti-aliasing 사용 여부, 세번째는 텍스트 컬러를 나타낸다 mainTimer = 80 - speed # 새로운 단어 생성 시간 ranNum = random.randrange(len(word_rect_lst)) # 새로운 좌표에 단어가 이미 있는지 while isLoc(wordsLst, ranNum): ranNum = random.randrange(len(word_rect_lst)) wordsLst.append([ textSurface, ranNum, list(word_rect_lst[ranNum]), 800, wordRan ]) # 단어Surface || 인덱스 || 좌표 || 시간 || 단어 wordsLst[-1][2][1] += 50 - (speed / 2) # 단어 떠오르고 지는 시간 조절 for words in wordsLst[::-1]: if words[3] <= 50 + (speed / 2): words[2][1] += 5 - (speed / 20) elif words[2][1] >= word_rect_lst[words[1]][1]: words[2][1] -= 5 + (speed / 20) words[3] -= 5 + (speed / 20) # 단어의 타이머가 소진되면 if words[3] <= 0: life.lifeDecrease() # 목숨 수 1 감소 heartLst.pop(life.getLife()) # 목숨 그림 감소 wordsLst.remove(words) # 단어 삭제 continue screen.blit(words[0], (words[2][0] + 40, words[2][1] - 100)) # 목숨 소진 시 게임 오버 화면 출력 if life.getLife() == 0: pygame.font.init() font = pygame.font.Font(None, 40) text = font.render("Score: " + str(score.getScore()), True, (255, 0, 0)) textRect = text.get_rect() textRect.centerx = screen.get_rect().centerx textRect.centery = screen.get_rect().centery + 24 screen.blit(gameover, (0, 0)) screen.blit(text, textRect) running = False pygame.display.flip() fpsClock.tick(FPS) # 키보드 이벤트 for e in pygame.event.get(): if e.type == pygame.QUIT: pygame.quit() if e.type == pygame.KEYDOWN: textBox.add_chr(pygame.key.name(e.key)) if e.key == pygame.K_SPACE: textBox.text += " " textBox.update() if e.key == pygame.K_BACKSPACE: textBox.text = textBox.text[:-1] textBox.update() if e.key == pygame.K_RETURN: # 엔터를 치면 위에 문자랑 같을시 위의 두더지가 사라지고 문자도 사라져야함. answer = textBox.text textBox.text = "" for words in wordsLst: if answer == words[4]: wordsLst.remove(words) score.scoreUp(difficulty) textBox.update() if e.key == pygame.K_ESCAPE: running = False mainTimer -= 1 - (speed / 100) # 시간의 흐름 sleep(5) # 5초 후 메인 창으로 복귀
def __init__(self): self.life = Life() self.reset()
def __init__(self, seed): self.seed = seed self.game = Life() self.screen = curses.initscr()
def __init__(self, manager): monome.Page.__init__(self, manager) Life.__init__(self)
#!/opt/local/bin/python from life import Life a = Life(200, 200) for i in range(1000): a.advance_history() a.play()
def create_lifes(game_settings, screen, stats, lifes): for number in range(stats.get_ships_left()): life = Life(game_settings, screen, number) life.set_position(len(lifes)) lifes.add(life)