class FachadaJuegos(): def __init__(self): self.laberinto = Laberinto() self.puzzle = Puzzle() self.ruta = Ruta() self.snake = Snake() self.evitandoVirus = EvitandoVirus() self.puntaje = 0 def arrancarJuego(self, nombreJuego): if nombreJuego == 'laberinto': self.laberinto.iniciarJuego() self.puntaje += self.laberinto.getPuntos() elif nombreJuego == 'puzzle': self.puzzle.iniciarJuego() self.puntaje += self.puzzle.getPuntos() elif nombreJuego == 'ruta': self.ruta.iniciarJuego() self.puntaje += self.ruta.getPuntos() self.ruta = Ruta() elif nombreJuego == 'snake': self.snake.iniciarJuego() self.puntaje += self.snake.getPuntos() elif nombreJuego == 'virus': self.evitandoVirus.iniciarJuego() self.puntaje += self.evitandoVirus.getPuntos() def getPuntaje(self): return self.puntaje
def reset(self): # reset env self.env = np.zeros((self.max_h, self.max_w)) # background self.env = self.draw_boundary(self.env) # Add player 1 head_x1, head_y1 = self.get_randoms() self.p1 = Snake(head_x1, head_y1, self.w, self.h) self.env = self.p1.draw(self.env, player=1) # Add player 2 head_x2, head_y2 = self.get_randoms() self.p2 = Snake(head_x2, head_y2, self.w, self.h) self.env = self.p2.draw(self.env, player=2) # Add food self.food_x, self.food_y = self.get_randoms() self.env[self.food_y, self.food_x] = CONSTANTS['food'] # Get player's states (v for vision) self.v1 = self.p1.look(self.env, self.agent_vision) self.v2 = self.p2.look(self.env, self.agent_vision) return np.hstack((self.v1.ravel(), (head_x1 - self.food_x, head_y1 - self.food_y))), self.v1, \ np.hstack((self.v2.ravel(), (head_x2 - self.food_x, head_y2 - self.food_y))), self.v2
def run_game(): # 游戏配置信息 game_setting = Setting() # 初始化游戏,并创建一个屏幕对象 pygame.init() fps_clock = pygame.time.Clock() # 图标 icon = pygame.image.load("res/snake.png") screen = pygame.display.set_mode( [game_setting.screen_width, game_setting.screen_width]) pygame.display.set_caption("Greedy Snake") pygame.display.set_icon(icon) # 创建一条蛇 snake = Snake(game_setting, screen) # 创建一个食物 food = Food(game_setting, screen, snake) # 游戏的主循环 while True: gf.keyboard_listener(game_setting, snake) snake.update() gf.snake_eat_food(snake, food) gf.update_screen(game_setting, screen, snake, food) fps_clock.tick(game_setting.snake_speed)
def __init__(self): self.laberinto = Laberinto() self.puzzle = Puzzle() self.ruta = Ruta() self.snake = Snake() self.evitandoVirus = EvitandoVirus() self.puntaje = 0
def __init__(self, ml = False): self._running = True self._display_surf = None if ml: speed = 10 else: speed = 200 self.game = Snake(speed) self.human = not ml
def main(stdscr): fps = 5 stdscr.timeout(1000 // fps) # hide cursor curses.curs_set(0) # init head at top left border = 2 stdscr.border(border) # h = Head(border, border, stdscr, '@') f = Food(border, border, stdscr, '$') s = Snake(border, border, stdscr) score = 0 while True: stdscr.clear() # index of keyboard # index = -1 if no key inserted in loop stdscr.addstr(1, 10, f'score: {score} type ESC to exit') # h.render() f.render() s.render() key = stdscr.getch() log('key:', key) s.update(key) # ESC == 27 if s.collid() or key == 27: break if s.head.coor == f.coor: f.reset() s.grow() score += 1
def __init__(self, maze_size=_MAZE_SIZE, start_location=Coordinate(int(_MAZE_SIZE / 2), int(_MAZE_SIZE / 2)), tick_interval=1): self._maze_size = maze_size self._snake = Snake(head=start_location) self._food = None self._running = False self._timer = None self._tick_interval = tick_interval self._tick_count = 0
def __init__(self): pygame.init() self.CLOCK = Clock() self.ROWS_COLS = 15 self.GRID_SIZE = 50 self.SCREEN_SIZE = self.GRID_SIZE * self.ROWS_COLS self.DISPLAY = display.set_mode((self.SCREEN_SIZE, self.SCREEN_SIZE)) self.BACKGROUND_COLOR = (0, 0, 0) self.GRID_COLOR = (100, 100, 100) self.SNAKE_COLOR = (0, 255, 0) self.apple_generator = AppleGenerator(self.ROWS_COLS, self.GRID_SIZE) self.apple = self.apple_generator.generate_apple(self.snake) mid = (self.ROWS_COLS // 2) * self.GRID_SIZE self.start_x_y = (mid, mid) self.snake = Snake(self.start_x_y, self.GRID_SIZE, self.SCREEN_SIZE, self.SNAKE_COLOR, self.spawn_apple) self.exit_clicked = None self.playing = None
def start_server(port='8080'): server = Battlesnake(Snake()) cherrypy.config.update({'server.socket_host': '0.0.0.0'}) cherrypy.config.update({ 'server.socket_port': int(os.environ.get('PORT', port)), }) print('Starting Battlesnake Server...') cherrypy.quickstart(server)
def __init__(self): self.fps = 30 self.fpsclock = pygame.time.Clock() self.view = View() self.snake_obj = Snake() pygame.time.set_timer(USEREVENT, 150) # ['base', 'menu', 'pause', 'ingame', 'gameover', 'locating_server', 'lan_game_mode'] self.screen = 'menu' self.on_menu = True self.on_pause = False self.thread_list = [] self.interface = Interface(main=self, view=self.view, snake=self.snake_obj)
def main(): board_size = 15 v = View(board_size) s = Snake(board_size) key_mapping = { 'H': s.DIR_UP, 'M': s.DIR_RIGHT, 'P': s.DIR_DOWN, 'K': s.DIR_LEFT } clear = lambda: os.system('cls') clear() while True: if msvcrt.kbhit(): msvcrt.getch() # skip 0xe0 key = msvcrt.getch().decode('utf-8') if key in key_mapping: if not s.update(key_mapping[key]): return else: if not s.update(None): return #print(s.get_food_x_y()) #print(s.get_coord_list()) v.update_gameboard(s.get_coord_list(), s.get_food_x_y()) time.sleep(0.1) clear = lambda: os.system('cls') clear()
class Env(): def __init__(self, max_width, max_height, init_width, init_height, display_width, display_height, agent_vision): self.max_w = max_width self.max_h = max_height self.w = init_width self.h = init_height self.disp_w, self.disp_h = display_width, display_height self.ACTION_SPACE = 4 self.agent_vision = agent_vision self.STATE_SPACE = (agent_vision * 2)**2 + 2 # agent_vision*2) #-------Increase the size of environment------# def change_size(self, w_change, h_change): self.w = min(self.w + w_change, self.max_w - self.agent_vision) self.h = min(self.h + h_change, self.max_h - self.agent_vision) return self.w, self.h #---------helpful function to get boundaries----------# def get_boundaries(self): odd_w, odd_h = self.w % 2, self.h % 2 mid_width, mid_height = int(self.max_w / 2), int(self.max_h / 2) x1, x2 = mid_width - int(self.w / 2), mid_height - 1 + int( self.w / 2) + odd_w y1, y2 = mid_width - int(self.h / 2), mid_height - 1 + int( self.h / 2) + odd_h return x1, x2, y1, y2 #-------------Returns random positions within the boundary--------------# def get_randoms(self, length=1): x1, x2, y1, y2 = self.get_boundaries() #logic to keep the snake AI inside the boundary if length > 1: max_w, max_h = self.max_w - length, self.max_h - length if x1 < length - 1: x1 = length - 1 if x2 > max_w: x2 = max_w if y1 < length - 1: y1 = length - 1 if y2 > max_h: y2 = max_h a = random.randint(x1, x2) b = random.randint(y1, y2) return a, b #-----Decide the playing region------# def draw_boundary(self, env): x1, x2, y1, y2 = self.get_boundaries() env[0:y1, :] = CONSTANTS['boundary'] env[y2 + 1:, :] = CONSTANTS['boundary'] env[y1:y2 + 1, 0:x1] = CONSTANTS['boundary'] env[y1:y2 + 1, x2 + 1:] = CONSTANTS['boundary'] return env #-------Reset the environment-------# def reset(self): # reset env self.env = np.zeros((self.max_h, self.max_w)) # background self.env = self.draw_boundary(self.env) # Add player 1 head_x1, head_y1 = self.get_randoms() self.p1 = Snake(head_x1, head_y1, self.w, self.h) self.env = self.p1.draw(self.env, player=1) # Add player 2 head_x2, head_y2 = self.get_randoms() self.p2 = Snake(head_x2, head_y2, self.w, self.h) self.env = self.p2.draw(self.env, player=2) # Add food self.food_x, self.food_y = self.get_randoms() self.env[self.food_y, self.food_x] = CONSTANTS['food'] # Get player's states (v for vision) self.v1 = self.p1.look(self.env, self.agent_vision) self.v2 = self.p2.look(self.env, self.agent_vision) return np.hstack((self.v1.ravel(), (head_x1 - self.food_x, head_y1 - self.food_y))), self.v1, \ np.hstack((self.v2.ravel(), (head_x2 - self.food_x, head_y2 - self.food_y))), self.v2 #-----Render the environment---------# def render(self, actions, states, stats, train=True, episode=-1, epsilon=-1, gamma=-1): disp_matrix = self.get_display_matrix(self.env) state1, state2 = self.get_display_matrix( states[0]), self.get_display_matrix(states[1]) disp_env = add_states(disp_matrix, state1, actions[0], left=True) disp_env = add_states(disp_env, state2, actions[1]) # sprinkle some info to the disp train_params = None if train: train_params = { 'Episode': episode, 'Epsilon': epsilon, 'Gamma': gamma } p1_params = {'Player': 1, 'stats': stats[0]} p2_params = {'Player': 2, 'stats': stats[1]} img = add_info(self.disp_w, self.disp_h, disp_env, p1_params, p2_params, train_params=train_params) #img2 = Image.fromarray(self.env) #img2 = np.array(img2.resize(self.max_w, self.max_h)) cv2.imshow("Sliterh_io", img) #cv2.imshow("AI v/s AI", self.env) #time.sleep(1) if cv2.waitKey(1) & 0xFF == ord('q'): #when Q is pressed print('Stop Execution') cv2.destroyAllWindows() quit() #------------Adds color to matrix------------------------------# @staticmethod def get_display_matrix(matrix): disp_matrix = np.ones( (*matrix.shape, 3), dtype=np.uint8) * 255 # background disp_matrix[np.where(matrix == CONSTANTS['boundary'])] = BOUNDARY_COLOR disp_matrix[np.where(matrix == CONSTANTS['p1'])] = PLAYER_COLORS[1] disp_matrix[np.where(matrix == CONSTANTS['p2'])] = PLAYER_COLORS[2] disp_matrix[np.where( matrix == CONSTANTS['p1_head'])] = PLAYER_HEAD_COLOR disp_matrix[np.where( matrix == CONSTANTS['p2_head'])] = PLAYER_HEAD_COLOR disp_matrix[np.where(matrix == CONSTANTS['food'])] = FOOD_COLOR return disp_matrix #----------Agent takes an action and environment changes--------# def step(self, action, player): info = 0 # 1 - food eaten # 2 - Hit opponent # 3 - Died on Boundary p = self.p1 if player == 1 else self.p2 opp_player = 2 if player == 1 else 1 done, reward = False, -1 # positive reward x1, x2, y1, y2 = self.get_boundaries() x, y = ACTION_RESULT[action] head_x, head_y = p.head_pos() new_x, new_y = head_x + x, head_y + y # new head positions # check outside boundary if new_x < x1 or new_x > x2 or new_y < y1 or new_y > y2: done = True reward = 0 info = 3 """ # check collision with other agents if self.env[new_y, new_x] == CONSTANTS[f'p{opp_player}'] and not done: done = True reward = -10 info = 2 """ # check if ate food if self.env[new_y, new_x] == CONSTANTS['food']: p.grow() self.env[new_y, new_x] = CONSTANTS['background'] self.food_x, self.food_y = self.get_randoms() self.env[self.food_y, self.food_x] = CONSTANTS['food'] reward = 50 info = 1 if not done: # p.grow() pass else: # Add something to info # player is dead, displaye a cross or red patch pass p.update(x, y) self.env[np.where(self.env == CONSTANTS[f'p{player}_head'])] = 0 self.env[np.where(self.env == CONSTANTS[f'p{player}'])] = 0 self.env = self.draw_boundary(self.env) # redraw the boundaries self.env = p.draw(self.env, player=player) # redraw the player #print(self.env) vision = p.look(self.env, self.agent_vision ) # Check if next state is required in case of done return np.hstack((vision.ravel(), (new_x - self.food_x, new_y - self.food_y))), reward, done, vision, info
from snake.snake import Snake # Start application if __name__ == '__main__': s = Snake() s.run()
def reset(self): self.snake = Snake(self.start_x_y, self.GRID_SIZE, self.SCREEN_SIZE, self.SNAKE_COLOR, self.spawn_apple) self.spawn_apple()
class Game: def __init__(self): pygame.init() self.CLOCK = Clock() self.ROWS_COLS = 15 self.GRID_SIZE = 50 self.SCREEN_SIZE = self.GRID_SIZE * self.ROWS_COLS self.DISPLAY = display.set_mode((self.SCREEN_SIZE, self.SCREEN_SIZE)) self.BACKGROUND_COLOR = (0, 0, 0) self.GRID_COLOR = (100, 100, 100) self.SNAKE_COLOR = (0, 255, 0) self.apple_generator = AppleGenerator(self.ROWS_COLS, self.GRID_SIZE) self.apple = self.apple_generator.generate_apple(self.snake) mid = (self.ROWS_COLS // 2) * self.GRID_SIZE self.start_x_y = (mid, mid) self.snake = Snake(self.start_x_y, self.GRID_SIZE, self.SCREEN_SIZE, self.SNAKE_COLOR, self.spawn_apple) self.exit_clicked = None self.playing = None def start(self): self.playing = True self.exit_clicked = False self.reset() while self.playing: self.CLOCK.tick(10) delay(50) if not self.exit_clicked: for event in pygame.event.get(): if event.type == pygame.QUIT: # noinspection PyAttributeOutsideInit self.exit_clicked = True self.playing = False # Doesn't close immediately. Will still run a few cycles. pygame.quit() if not self.exit_clicked: self.snake.move() self.playing = self.playing and not self.snake.has_collided if self.playing: self.draw_game() elif not self.exit_clicked: print('Score: ', len(self.snake.body) + 1) self.message_box('You lost!', 'Play again?') self.reset() # noinspection PyAttributeOutsideInit self.playing = True def spawn_apple(self): self.apple = self.apple_generator.generate_apple(self.snake) self.snake.set_apple(self.apple) def reset(self): self.snake = Snake(self.start_x_y, self.GRID_SIZE, self.SCREEN_SIZE, self.SNAKE_COLOR, self.spawn_apple) self.spawn_apple() def draw_game(self): self.DISPLAY.fill(self.BACKGROUND_COLOR) self.draw_grid() self.snake.draw(self.DISPLAY) self.apple.draw(self.DISPLAY) display.update() def draw_grid(self): x, y = 0, 0 for i in range(self.ROWS_COLS): x += self.GRID_SIZE y += self.GRID_SIZE draw.line(self.DISPLAY, self.GRID_COLOR, (x, 0), (x, self.SCREEN_SIZE)) draw.line(self.DISPLAY, self.GRID_COLOR, (0, y), (self.SCREEN_SIZE, y)) @staticmethod def message_box(subject, content): root = tk.Tk() root.attributes("-topmost", True) root.withdraw() messagebox.showinfo(subject, content) # noinspection PyBroadException try: root.destroy() except: pass
def change_snake(self): self.snake = Snake() self.main.snake_obj = self.snake self.snake.interface = self
def main(): snake = Snake(SCREEN_WIDTH, SCREEN_HEIGHT) snake.play()
class game_main: def __init__(self): self.fps = 30 self.fpsclock = pygame.time.Clock() self.view = View() self.snake_obj = Snake() pygame.time.set_timer(USEREVENT, 150) # ['base', 'menu', 'pause', 'ingame', 'gameover', 'locating_server', 'lan_game_mode'] self.screen = 'menu' self.on_menu = True self.on_pause = False self.thread_list = [] self.interface = Interface(main=self, view=self.view, snake=self.snake_obj) def main(self): fps = self.fps fpsclock = self.fpsclock view = self.view while True: view.show('base') if self.on_menu or self.on_pause: view.show(self.screen) for event in pygame.event.get(): self.event_parser(event) else: if self.snake_obj.game_over: pygame.time.set_timer(USEREVENT, 0) view.show('gameover') for event in pygame.event.get(): if event.type == KEYUP and event.key == K_ESCAPE: self.change_screen('pause') elif event.type == KEYDOWN and event.key == K_UP: self.snake_obj.change_direction('U') elif event.type == KEYDOWN and event.key == K_DOWN: self.snake_obj.change_direction('D') elif event.type == KEYDOWN and event.key == K_LEFT: self.snake_obj.change_direction('L') elif event.type == KEYDOWN and event.key == K_RIGHT: self.snake_obj.change_direction('R') elif event.type == KEYDOWN and event.key == K_SPACE: if self.snake_obj.game_over: self.interface.change_snake() pygame.time.set_timer(USEREVENT, 200) elif event.type == USEREVENT: self.snake_obj.move_snake() elif event.type == USEREVENT+2: self.snake_obj.item_effect_countdown() view.show_ingame() pygame.display.update() fpsclock.tick(fps) def event_parser(self, event): view = self.view conn = self.interface.conn if event.type == pygame.QUIT or (event.type == KEYUP and event.key == K_ESCAPE): if self.screen == 'locating_server': self.change_screen('menu') else: if conn: conn.close() pygame.quit() sys.exit() elif event.type == USEREVENT+1: view.cll_locating_server.set_next_true() if conn.is_connected(): pygame.time.set_timer(USEREVENT+1, 0) self.screen = 'lan_game_mode' elif event.type == KEYDOWN and event.key == K_UP: view.current_menu.set_prev_true() elif event.type == KEYDOWN and event.key == K_DOWN: view.current_menu.set_next_true() elif event.type == KEYDOWN and event.key == K_RETURN: current_selection = view.current_menu.get_true() if current_selection.data[0] == "PLAY" or current_selection.data[0] == "RESUME": self.change_screen('ingame') elif current_selection.data[0] == "JOIN SERVER": if conn is None: self.interface.set_connection(Connection(client=True)) conn_thread = threading.Thread(target=self.interface.conn.client.find_server) conn_thread.start() self.thread_list.append(conn_thread) self.screen = 'locating_server' pygame.time.set_timer(USEREVENT+1, 250) elif current_selection.data[0] == "BACK TO MENU" or current_selection.data[0] == "RESTART": self.interface.change_snake() pygame.time.set_timer(USEREVENT, 200) self.change_screen('menu') if current_selection.data[0] == "RESTART": self.change_screen('ingame') elif current_selection.data[0] == "QUIT": if conn: conn.close() pygame.quit() sys.exit() def change_screen(self, screen): if screen == 'menu': self.on_menu = True self.on_pause = False elif screen == 'pause': self.on_menu = False self.on_pause = True else: self.on_menu = False self.on_pause = False self.screen = screen
def main(self, screen): screen.fill((0, 0, 0)) tutorial1 = """Geraldo é uma cobrinha sapeca e que vive faminta. Sua comida favorita é a fruta maça.""" tutorial2 = """Porém Geraldo é bem especifico, ele só come maçãs que são de numero primo no pé.""" tutorial3 = """INSTRUÇÔES""" tutorial4 = """Para isso ajude Geraldo a se alimentar capturando apenas as maçãs com numeros primos""" tutorial5 = """E utilizando as setas do teclado para se mover""" ##### TUTORIAL ######################## score_font = pygame.font.Font('freesansbold.ttf', 13) score_screen = score_font.render(f'{tutorial1}', True, (255, 255, 255)) score_rect = score_screen.get_rect() score_rect.midtop = (600 / 2, 10) screen.blit(score_screen, score_rect) score_font = pygame.font.Font('freesansbold.ttf', 13) score_screen = score_font.render(f'{tutorial2}', True, (255, 255, 255)) score_rect = score_screen.get_rect() score_rect.midtop = (600 / 2, 50) screen.blit(score_screen, score_rect) score_font = pygame.font.Font('freesansbold.ttf', 13) score_screen = score_font.render(f'{tutorial3}', True, (255, 255, 255)) score_rect = score_screen.get_rect() score_rect.midtop = (600 / 2, 100) screen.blit(score_screen, score_rect) score_font = pygame.font.Font('freesansbold.ttf', 13) score_screen = score_font.render(f'{tutorial4}', True, (255, 255, 255)) score_rect = score_screen.get_rect() score_rect.midtop = (600 / 2, 150) screen.blit(score_screen, score_rect) score_font = pygame.font.Font('freesansbold.ttf', 13) score_screen = score_font.render(f'{tutorial5}', True, (255, 255, 255)) score_rect = score_screen.get_rect() score_rect.midtop = (600 / 2, 200) screen.blit(score_screen, score_rect) pygame.display.update() pygame.time.wait(9000) snake_skin = pygame.Surface((self.BLOCK_SIZE, self.BLOCK_SIZE)) snake_skin.fill((255, 255, 255)) self.snake = Snake(snake_skin, self.screen_size) prime_apple_sprite = pygame.Surface((self.BLOCK_SIZE, self.BLOCK_SIZE)) prime_apple_sprite.fill((255, 0, 0)) prime_apple = Apple( prime_apple_sprite, # sprite self.on_grid_random(), # pos self.prime_apple_randomizer(), # num pygame.font.SysFont("arial", self.FONT_SIZE) # font ) normal_apple_sprite = pygame.Surface( (self.BLOCK_SIZE, self.BLOCK_SIZE)) normal_apple_sprite.fill((255, 0, 0)) normal_apple = Apple( normal_apple_sprite, # sprite self.on_grid_random(), # pos self.normal_apple_randomizer(), # num pygame.font.SysFont("arial", self.FONT_SIZE) # font ) clock = pygame.time.Clock() while True: """ This is the main looping of the game, resposible for update the screen,snake and apples """ clock.tick(10 if self.snake.fast else 5) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() exit() if event.type == KEYDOWN: self.snake.listen(event) if event.key == K_ESCAPE: return if self.snake.collision(prime_apple.pos): prime_apple.change(self.on_grid_random(), self.prime_apple_randomizer()) normal_apple.change(self.on_grid_random(), self.normal_apple_randomizer()) self.snake.grow() self.snake.counter = self.snake.counter + 1 if self.snake.collision(normal_apple.pos): self.snake.snake_reset() prime_apple.change(self.on_grid_random(), self.prime_apple_randomizer()) normal_apple.change(self.on_grid_random(), self.normal_apple_randomizer()) if self.snake.boundry_collision( ): # Check the collision with boudaries game_over = True self.game_over_screen(screen) return self.snake.update() screen.fill((0, 0, 0)) prime_apple.drawn(screen, 20) normal_apple.drawn(screen, 20) self.snake.drawn(screen, self.BLOCK_SIZE) pygame.display.update()
class SnakeGame: FONT_SIZE = 18 PRIME_NUMBERS = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 ] BLOCK_SIZE = 20 # Size of blocks def __init__(self, screen_size): self.screen_size = screen_size // self.BLOCK_SIZE # The width and height of the screen in number of blocks def mul(self, t, n): return (t[0] * n, t[1] * n) def on_grid_random(self): """ This function calculate a random position for a object on the screen :returns: tuple: Random position """ x = random.randint(0, self.screen_size - 2) y = random.randint(0, self.screen_size - 2) return (x, y) def collision(self, c1, c2): return (c1[0] == c2[0]) and (c1[1] == c2[1]) def prime_apple_randomizer(self): """ This function choose a random prime number from the self.PRIME_NUMBERS list :return: int: Random prime number """ number = random.choice(self.PRIME_NUMBERS) return int(number) def normal_apple_randomizer(self): """ This function chosse a not-prime random number between 0 and 99 :return: int: """ number = random.randint(0, 99) while number in self.PRIME_NUMBERS: number = random.randint(0, 99) return number def main(self, screen): screen.fill((0, 0, 0)) tutorial1 = """Geraldo é uma cobrinha sapeca e que vive faminta. Sua comida favorita é a fruta maça.""" tutorial2 = """Porém Geraldo é bem especifico, ele só come maçãs que são de numero primo no pé.""" tutorial3 = """INSTRUÇÔES""" tutorial4 = """Para isso ajude Geraldo a se alimentar capturando apenas as maçãs com numeros primos""" tutorial5 = """E utilizando as setas do teclado para se mover""" ##### TUTORIAL ######################## score_font = pygame.font.Font('freesansbold.ttf', 13) score_screen = score_font.render(f'{tutorial1}', True, (255, 255, 255)) score_rect = score_screen.get_rect() score_rect.midtop = (600 / 2, 10) screen.blit(score_screen, score_rect) score_font = pygame.font.Font('freesansbold.ttf', 13) score_screen = score_font.render(f'{tutorial2}', True, (255, 255, 255)) score_rect = score_screen.get_rect() score_rect.midtop = (600 / 2, 50) screen.blit(score_screen, score_rect) score_font = pygame.font.Font('freesansbold.ttf', 13) score_screen = score_font.render(f'{tutorial3}', True, (255, 255, 255)) score_rect = score_screen.get_rect() score_rect.midtop = (600 / 2, 100) screen.blit(score_screen, score_rect) score_font = pygame.font.Font('freesansbold.ttf', 13) score_screen = score_font.render(f'{tutorial4}', True, (255, 255, 255)) score_rect = score_screen.get_rect() score_rect.midtop = (600 / 2, 150) screen.blit(score_screen, score_rect) score_font = pygame.font.Font('freesansbold.ttf', 13) score_screen = score_font.render(f'{tutorial5}', True, (255, 255, 255)) score_rect = score_screen.get_rect() score_rect.midtop = (600 / 2, 200) screen.blit(score_screen, score_rect) pygame.display.update() pygame.time.wait(9000) snake_skin = pygame.Surface((self.BLOCK_SIZE, self.BLOCK_SIZE)) snake_skin.fill((255, 255, 255)) self.snake = Snake(snake_skin, self.screen_size) prime_apple_sprite = pygame.Surface((self.BLOCK_SIZE, self.BLOCK_SIZE)) prime_apple_sprite.fill((255, 0, 0)) prime_apple = Apple( prime_apple_sprite, # sprite self.on_grid_random(), # pos self.prime_apple_randomizer(), # num pygame.font.SysFont("arial", self.FONT_SIZE) # font ) normal_apple_sprite = pygame.Surface( (self.BLOCK_SIZE, self.BLOCK_SIZE)) normal_apple_sprite.fill((255, 0, 0)) normal_apple = Apple( normal_apple_sprite, # sprite self.on_grid_random(), # pos self.normal_apple_randomizer(), # num pygame.font.SysFont("arial", self.FONT_SIZE) # font ) clock = pygame.time.Clock() while True: """ This is the main looping of the game, resposible for update the screen,snake and apples """ clock.tick(10 if self.snake.fast else 5) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() exit() if event.type == KEYDOWN: self.snake.listen(event) if event.key == K_ESCAPE: return if self.snake.collision(prime_apple.pos): prime_apple.change(self.on_grid_random(), self.prime_apple_randomizer()) normal_apple.change(self.on_grid_random(), self.normal_apple_randomizer()) self.snake.grow() self.snake.counter = self.snake.counter + 1 if self.snake.collision(normal_apple.pos): self.snake.snake_reset() prime_apple.change(self.on_grid_random(), self.prime_apple_randomizer()) normal_apple.change(self.on_grid_random(), self.normal_apple_randomizer()) if self.snake.boundry_collision( ): # Check the collision with boudaries game_over = True self.game_over_screen(screen) return self.snake.update() screen.fill((0, 0, 0)) prime_apple.drawn(screen, 20) normal_apple.drawn(screen, 20) self.snake.drawn(screen, self.BLOCK_SIZE) pygame.display.update() def game_over_screen(self, screen): """ This is the Game over menu looping. Responsible for the game-over screen and score """ while True: game_over_font = pygame.font.Font('freesansbold.ttf', 75) game_over_screen = game_over_font.render(f'Game Over', True, (255, 255, 255)) game_over_rect = game_over_screen.get_rect() game_over_rect.midtop = (600 / 2, 10) screen.blit(game_over_screen, game_over_rect) score_font = pygame.font.Font('freesansbold.ttf', 30) score_screen = score_font.render( f'Pontuação final: {self.snake.counter}', True, (255, 255, 255)) score_rect = score_screen.get_rect() score_rect.midtop = (600 / 2, 100) screen.blit(score_screen, score_rect) pygame.display.update() pygame.time.wait(500) while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() exit() elif event.type == KEYDOWN: if event.key == K_RETURN or event.key == K_KP_ENTER: self.main(screen) elif event.key == K_ESCAPE: return
class PlaySnake: def __init__(self, maze_size=_MAZE_SIZE, start_location=Coordinate(int(_MAZE_SIZE / 2), int(_MAZE_SIZE / 2)), tick_interval=1): self._maze_size = maze_size self._snake = Snake(head=start_location) self._food = None self._running = False self._timer = None self._tick_interval = tick_interval self._tick_count = 0 @property def score(self): return self._snake.length @property def running(self): return self._running @property def direction(self): return self._snake.heading @direction.setter def direction(self, direction): self._snake.heading = direction @property def game_map(self): game_map = [[0 for x in range(self._maze_size)] for y in range(self._maze_size)] for segment in self._snake.map: game_map[segment.x][segment.y] = 1 game_map[self._snake.head.x][self._snake.head.y] = 2 game_map[self._food.location.x][self._food.location.y] = 3 return game_map def start(self): if self._running: return self._timer = Timer(self._tick_interval, self._tick) self._food = Food(maze_size=self._maze_size, snake_map=self._snake.map) self._timer.start() self._running = True def stop(self): if self._timer: self._timer.cancel() self._running = False self._timer = None def _tick(self): if not self._running: return self._timer = Timer(self._tick_interval, self._tick) self._timer.start() if self._snake.new_head(self._snake.heading) == self._food.location: self._snake.move(maze_size=self._maze_size, grow=True) self._food = Food(maze_size=self._maze_size, snake_map=self._snake.map) else: self._snake.move(maze_size=self._maze_size, grow=False) if not self._snake.alive: self.stop()
class App: windowWidth = 800 windowHeight = 600 game = 0 human = True robot = None def __init__(self, ml = False): self._running = True self._display_surf = None if ml: speed = 10 else: speed = 200 self.game = Snake(speed) self.human = not ml def on_init(self): pygame.init() self._display_surf = pygame.display.set_mode((self.windowWidth, self.windowHeight), pygame.HWSURFACE) pygame.display.set_caption('Snake ML') self.game.on_init() if not self.human: self.robot = Robot(100, 1) self._running = True def on_event(self, event): if event.type == QUIT: self._running = False def on_loop(self): pass def on_render(self): self._display_surf.fill((0,0,255)) self.game.on_render(self._display_surf) pygame.display.flip() def on_cleanup(self): pygame.quit() def on_execute(self): if self.on_init() == False: self._running = False if not self.human: population = 10 print "Starting population generation...", sys.stdout.flush() genLearn = GeneticLearning(0, population, 0.001, self.game.height * self.game.width, 1) genIndex = 0 self.robot.network = genLearn.generationWeights[genIndex] print "done! starting" genLearn.onStart(genIndex) while( self._running ): pygame.event.pump() if self.human: keys = pygame.key.get_pressed() else: gameState = self.game.getGameState() keys = self.robot.calculateKey(gameState) self.game.update(keys) keys = pygame.key.get_pressed() if (keys[K_ESCAPE]): self._running = False if not self.human and (self.game.hasWon() <= 1 or self.game.player.dead): genLearn.onComplete(genIndex, self.game.score) if genIndex == population - 1: genLearn.onAllComplete(cross = False, createNew=1) genIndex = 0 print "All done, scores:" print genLearn.generationResult else: genIndex += 1 self.robot.network = genLearn.generationWeights[genIndex] self.game.reset() pygame.event.pump() keys = pygame.key.get_pressed() if (keys[K_ESCAPE]): self._running = False genLearn.onStart(genIndex) self.on_render() self.on_cleanup()
def __init__(self, client=True, server=False): self.server = Server() if server else None self.client = Client() self.enemy_obj = Snake() self.interface = None
from snake.snake import Snake from snake.settings import Settings from snake.spec_helper import * with description('Snake') as self: with it('has a default length'): snake = Snake() expect(snake.length).to(equal(3)) with context('no velocity'): with it('does not grow'): snake = Snake() snake.tick(1000) expect(snake.length).to(equal(3)) with context('positive velocity'): with it('grows at the expected rate'): snake = Snake() snake.post = Dummy() snake.queue_growth(2) snake.set_velocity(Settings.snake_size / 100.0, 0 ) # Moving right, growing snake.tick(100) expect(snake.length).to(equal(4)) expect(snake.growing).to(equal(1)) expect(snake.head_pt.x).to(equal(Settings.snake_size * 3)) expect(snake.head_pt.y).to(equal(0))