def createDino(tipo=1): if tipo == 1: d = Dino2(context, 43, 47, position=random.randint(10, 25)) else: d = Dino(context, 43, 47, position=random.randint(10, 25)) d.set_color(random_color()) return d
def __init__(self, context, sizex=-1, sizey=-1, position=15, redeNeural=None): Dino.__init__(self, context, sizex, sizey, position) if (redeNeural != None): self.redeNeural = redeNeural else: self.redeNeural = RedeNeural()
def reset(self): self.curses_initialize_screen() self.set_max_dimensions() self.ground_level = self.rows_max - 3 self.ground_string = '=' * (self.cols_max - 3) self.dino = Dino(self) self.score = Score(self.stdscr) self.initialize_obstacles() self.show_loading_animation()
def main(): game = Game() player = Dino(50, game.win_height - 250, 64, 64) game.add_player(player) spawn_thresholds = [1.5, 1.75, 2, 2.5, 3, 3.50] enemy_spawn_threshold = 3.5 time_since_last_spawn = enemy_spawn_threshold last_time = time_millis() max_speedups = 3 speedups = 0 speedup_after = 15.0 speedup_timer = 0 # Takto lze změnit texturu země ve hře # Případně lze dodat vlastní textury do složky resources a následně # Lze využít i vlastních textur # game.change_ground('resources/grass.png') # game.change_ground('resources/grass_alt.png') # game.change_ground('resources/sand.png') while game.window_is_open: # Počítání časového rozdílu current_time = time_millis() delta = (current_time - last_time) / 1000 game.tick(delta) last_time = current_time # Logika vytváření nepřátelských entit time_since_last_spawn += delta if time_since_last_spawn >= enemy_spawn_threshold: game.add_enemy(get_enemy()) time_since_last_spawn = 0 enemy_spawn_threshold = random.choice(spawn_thresholds) # Kolize s nepřátelskými entitami for enemy in game.enemies: if player.collides_with(enemy): player.die() # Logika zrychlování hry speedup_timer += delta if speedups < max_speedups and speedup_timer >= speedup_after: speedup_timer = 0 game.increase_speed()
def main(): """ Run the rendering loop for the scene. """ viewer = Viewer() origin = (-100,-120, -100) widthScale = 3 ground = Ground(origin, widthScale, 0.8) viewer.add(ground) #Generate trees according to a uniform law for appearance trees = [] for x, z in ground.iterPos(): if(not(x%10) and not(z%10)): #generating if(np.random.uniform() > 0.75): tree = Tree(x*widthScale, ground.getHeight(x, z)+2, z*widthScale) trees.append(tree) viewer.add(tree.node) control = Control() viewer.add(control) dino = Dino(ground) viewer.add(dino) viewer.run(dino)
class MyScene(scene.Scene): def setup(self): self.background_color = 'white' self.dino = Dino() # 这个sb pythonista作者设置的texture中心点作为坐标,而且与opencv坐标不同,|_这种坐标 self.add_child(self.dino) self.grounds = Grounds() self.add_child(self.grounds) self.clouds = Clouds(-2, self.size.x) self.add_child(self.clouds) self.cactuses = Cactuses(self.size.x) self.add_child(self.cactuses) self.score_boards = ScoreBoards() self.add_child(self.score_boards) self.middle_x = self.size.x / 2 def check_collision(self): if self.cactuses.check_collision(self.dino.left_buttom_coord, self.dino.size): self.dino.is_dead = True self.dino.update() self.paused = True def update(self): self.dino.update() self.grounds.update() self.clouds.update() self.cactuses.update() self.score_boards.update() self.check_collision() def touch_began(self, touch): if touch.location.x < self.middle_x: self.dino.start_jump() else: self.dino.start_duck() def touch_ended(self, touch): self.dino.end_duck()
def introscreen(): temp_dino = Dino(44,47) temp_dino.isBlinking = True gameStart = False callout,callout_rect = load_image('call_out.png',196,45,-1) callout_rect.left = width*0.05 callout_rect.top = height*0.4 temp_ground,temp_ground_rect = load_sprite_sheet('ground.png',15,1,-1,-1,-1) temp_ground_rect.left = width/20 temp_ground_rect.bottom = height logo,logo_rect = load_image('logo.png',240,40,-1) logo_rect.centerx = width*0.6 logo_rect.centery = height*0.6 while not gameStart: if pygame.display.get_surface() == None: print("Couldn't load display surface") return True else: for event in pygame.event.get(): if event.type == pygame.QUIT: return True if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE or event.key == pygame.K_UP: temp_dino.isJumping = True temp_dino.isBlinking = False temp_dino.movement[1] = -1*temp_dino.jumpSpeed temp_dino.update() if pygame.display.get_surface() != None: screen.fill(background_col) screen.blit(temp_ground[0],temp_ground_rect) if temp_dino.isBlinking: screen.blit(logo,logo_rect) screen.blit(callout,callout_rect) temp_dino.draw(screen) pygame.display.update() clock.tick(FPS) if temp_dino.isJumping == False and temp_dino.isBlinking == False: gameStart = True
def evaluate(self, genome, generation, genome_id): """Generate a game, test the genome and return its fitness. Keyword arguments: genome -- genome to test generation -- number of the current generation genome_id -- genome id in the current generation """ # create neural network from genome. net = NEAT.NeuralNetwork() genome.BuildPhenotype(net) # create player and . player = Dino_player_neat(net) text = "generation : " + str(generation) + " || genome : " + str( genome_id) the_game = Dino(player, text) fitness = the_game.on_execute(start_immediately=True) return fitness
def createDNA(self, p: int) -> None: pop: list = [] if self.__dino is None: for i in range(p): pop.append(Dino()) self.__dino = pop else: if p > len(self.__dino): for i in range(len(self.__dino), p): self.__dino.append(Dino()) else: index = len(self.__dino) - 1 while len(self.__dino) >= p: del self.__dino[index] index -= 1
def setup(self): self.background_color = 'white' self.dino = Dino() # 这个sb pythonista作者设置的texture中心点作为坐标,而且与opencv坐标不同,|_这种坐标 self.add_child(self.dino) self.grounds = Grounds() self.add_child(self.grounds) self.clouds = Clouds(-2, self.size.x) self.add_child(self.clouds) self.cactuses = Cactuses(self.size.x) self.add_child(self.cactuses) self.score_boards = ScoreBoards() self.add_child(self.score_boards) self.middle_x = self.size.x / 2
def main(): dino_img = load_dino() # imshow(dino_img) # show() dino = Dino(dino_img) dino.init() dino.start()
def reset(self): self.gamespeed = 4 self.startMenu = False self.gameOver = False self.gameQuit = False self.playerDino = Dino(44,47) self.new_ground = Ground(-1*self.gamespeed) self.scb = Scoreboard() self.highsc = Scoreboard(self.width*0.78) self.counter = 0 self.t_reward = 0 self.crow_height_index = 0 self.nearest = 800 self.second_nearest = 1000 self.action_complete = True self.cacti = pygame.sprite.Group() self.crows = pygame.sprite.Group() self.last_obstacle = pygame.sprite.Group() Cactus.containers = self.cacti Crow.containers = self.crows self.old_states = [] self.new_states = [] self.old_states.append(self.new_ground.speed/-4) self.old_states.append(np.digitize(9.0, self.discrete_spaces)) self.old_states.append(np.digitize(9.0, self.discrete_spaces)) self.old_states.append(self.crow_height_index) # self.old_states.append("Crouch" if self.playerDino.rect[2] != 44 else " standing") self.old_states.append(0 if self.playerDino.rect[2] != 44 else 1) self.play() return np.array(self.old_states, dtype=np.float64)
def __init__(self, args): super(Gym).__init__() self.args = args # environment parameters self.dino = Dino(args) # game parameters self.highscore = load_highscore(args.highscore_filename) self.t = 0 # to play with an AI self.isHuman = (args.agent == "human") if not self.isHuman: self.agent = AIAgent(args, self.dino) # load saved parameters if self.args.load_save: load_agent(self.agent, self.args.save_filename) # listen to user inputs self.inputs_list = [] threading.Thread(target=input_thread, args=(self.inputs_list, )).start()
def run_game(): crrnt_sttngs = Settings() # Screen vars screen_width = crrnt_sttngs.screen_width screen_height = crrnt_sttngs.screen_height bg_color = crrnt_sttngs.bg_color # Game vars init_speed = crrnt_sttngs.init_speed # Misc vars logo = pygame.image.load("assets/dino_still_ground.png") # Initialize the game and create a screen object pygame.init() pygame.display.set_icon(logo) pygame.display.set_caption("Python Port of chrome://dino") screen = pygame.display.set_mode([screen_width, screen_height]) # Init dino and cactus start_bt = Button(crrnt_sttngs, screen, "Play!") dino = Dino(screen, crrnt_sttngs) cactus = Cactus(screen, crrnt_sttngs, 'small') # Main loop of the game print("[INFO] The game starts.") #cactuses = Group() while True: # Use the ioresolv module to check events ioresolv.check_events(dino) dino.update(crrnt_sttngs.dhmax) sleep(1/crrnt_sttngs.init_speed) cactus.update() start_bt.update()
def run_game(): pygame.init() set = Settings() screen = pygame.display.set_mode((set.screen_width, set.screen_height)) pygame.display.set_caption("Dino Run") # Creates background sun = Sun(set, screen) ct1 = City(set, screen, 1) ct2 = City(set, screen, 2) # Active game scoreboard sb = Scoreboard(set, screen) # High score shows when game paused high_score = Scoreboard(set, screen) # Playbutton - to start game play_button = Button(set, screen, "Play") # Creates game objects dino = Dino(set, screen) cacti = Group() dino.jump() # Initialize jump for player while True: # Checks jump, fireball, dino/cacti collisions gf.check_events(set, play_button, dino, cacti) if set.play: # Updates city movement ct1.update() ct2.update() sb.prep_score(set) # Preps scoreboard if set.play: # Checks for fireball collision or offscreen cacti gf.update_cacti(set, cacti, dino.fireball) dino.update(set) # Updates dino, fireball, explosion gf.check_score(set, dino, cacti) if random.randint(0, 10) > 8: # Need better spawning method gf.make_cactus(set, screen, cacti) else: high_score.prep_score(set, True) high_score.prep_score(set, True) high_score.show_score() gf.draw_background(set, ct1, ct2, sun, sb) gf.draw_screen(set, play_button, high_score, dino, cacti) sleep(.03) # Gets around 34 frames a second
def loadDNA(self, directory: str) -> bool: elements: list ret: bool = False if exists(directory): if isdir(directory): elements = listdir(directory) aux: Dino = None self.__dino = [] for i in elements: if i[-2:] == 'h5': try: aux = Dino() aux.model.load_weights(directory + i) self.__dino.append(aux) except ValueError as error: self.destroyDNA() raise ValueError(error) except TypeError as error: self.destroyDNA() raise TypeError(error) except OSError: self.destroyDNA() raise OSError(error) else: ret = True else: raise TypeError( "este diretorio não possui arquivos que possa ser carregados para o modelo" ) else: raise ValueError("O destino informado não é um diretorio.") else: raise ValueError("O destino informado não existe.") return ret
return None if len(arguments) != 0 and len(sys.argv) == 1: return arguments else: return None if __name__ == "__main__": arguments = verify_arguments() if arguments is None: print(f'Usage: python {sys.argv[0]} [ --type (human|random|neat \ [--population <size>] [--generations <size>]) ] ') elif "type" in arguments: if arguments["type"] == "human": player = Dino_player() theDino = Dino(player) theDino.on_execute() elif arguments["type"] == "random": player = Dino_player_random() theDino = Dino(player) theDino.on_execute() else: data = dict() if "population" in arguments: data["population_size"] = arguments["population"] if "generations" in arguments: data["generations"] = arguments["generations"] cycle = NEAT_trainer(**data) cycle.start_cycle() else: player = Dino_player()
def main(genomes, config): nn = [] #lista sieci neurnowych ge = [] #lista genomów dinos = [] #lista dino os.environ['SDL_VIDEO_WINDOW_POS'] = '400,50' # ustiawienie pozycji okna window = pygame.display.set_mode( (WIN_WIDTH, WIN_HEIGHT)) # stworzenie okna for _, g in genomes: net = neat.nn.FeedForwardNetwork.create( g, config) #stowrzenie sieci neuronowej nn.append(net) #dodanie jej do listy sieci dinos.append(Dino(50, 450)) #stworzenie dino i dodanie go do listy g.fitness = 0 #ustawienie funkcji fitness ge.append(g) #dodanie genomu do listy run = True bg = Background(0) cactuses = [Cactus()] score = 0 add_cactus = False while run: cactus_ind = 0 if len(dinos) > 0: if len(cactuses) > 1 and dinos[ 0].x > cactuses[0].x + cactuses[0].IMG.get_width(): cactus_ind = 1 else: run = False for event in pygame.event.get(): if event.type == pygame.QUIT: run = False pygame.quit() quit() for x, dino in enumerate(dinos): dino.move() output = nn[x].activate((dino.y, dino.x - cactuses[cactus_ind].x)) if output[0] > 0.5 and not dino.is_jumping: dino.jump() ge[x].fitness -= 1.5 remove_cactus = [] for cactus in cactuses: for x, dino in enumerate(dinos): if not cactus.passed and cactus.x < dino.x: # pokonanie przez Dino score += 1 cactus.passed = True add_cactus = True if cactus.collide(dino): dinos.pop(x) nn.pop(x) ge.pop(x) if cactus.x + cactus.IMG.get_width() < 0: # wyjsce poza ekran remove_cactus.append(cactus) for cactus in cactuses: cactus.move() if add_cactus: cactuses.append(Cactus()) for g in ge: g.fitness += 3 add_cactus = False for r in remove_cactus: cactuses.remove(r) bg.move() draw_window(window, dinos, bg, cactuses, score)
def dino_game(): # Instansiasi objek menu = Menu() dino = Dino(road_height) enemy = EnemyMgr(road_height) # Frame mula-mula frame = 0 while True: # Tampilkan background game display.blit(background, (0, 0)) # Dapatkan informasi event saat ini for event in pygame.event.get(): # Keluar dari game jika layar ditutup if event.type == pygame.QUIT: return # Game sedang berjalan elif menu.state == "RUN": if event.type == pygame.KEYDOWN: # Tekan UP untuk melompat if event.key == pygame.K_UP: dino.jump() # Tekan DOWN untuk menunduk elif event.key == pygame.K_DOWN: dino.duck() # Tekan ESC untuk berhenti sejenak elif event.key == pygame.K_ESCAPE: menu.pause() # Kembali berjalan sesudah menekan tombol elif event.type == pygame.KEYUP: dino.walk() # Game sedang berhenti pada menu elif menu.state != "RUN": if event.type == pygame.KEYDOWN: # Tekan UP untuk pilihan sebelumnya if event.key == pygame.K_UP: menu.prev() # Tekan DOWN untuk pilihan selanjutnya elif event.key == pygame.K_DOWN: menu.next() # Tekan ENTER untuk memilih pilihan menu elif event.key == pygame.K_RETURN: # Posisi pilihan pada menu pause sebagai basis if menu.state == "PAUSE": choose = menu.choose # Sesuaikan posisi pilihan seperti menu pause elif menu.state == "DIED": choose = menu.choose + 1 # Memilih "Lanjutkan permainan" if choose == 0: menu.unpause() # Memilih "Permainan baru" elif choose == 1: menu.reset() dino.reset() enemy.reset(display) # Memilih "Keluar" elif choose == 2: return # Update gerakan dino dino.update(display, frame, menu) # Update musuh, skor, dan cek tabrakan enemy.update(display, frame, menu, dino) # Update gerakan menu dan layar menu.update(display) pygame.display.update() # Atur frame untuk loop selanjutnya frame = (frame + 1) % menu.speed fps.tick(menu.speed)
class DinoGameEnv: def __init__(self): self.crow_height_index = 0 self.i = 0 self.high_score = 0 self.nearest = 800 self.second_nearest = 1000 self.t_reward = 0 self.discrete_spaces = np.linspace(1, 8, num=25) self.action_complete = True self.old_states = [] self.new_states = [] self.allow_rendering = False pygame.mixer.pre_init(44100, -16, 2, 2048) # fix audio delay pygame.init() self.scr_size = (self.width,self.height) = (600,150) self.FPS = 60 # background_col = (235,235,235) self.background_col = (255,255,255) self.clock = pygame.time.Clock() self.screen = pygame.display.set_mode(self.scr_size) pygame.display.set_caption("T-Rex Rush") temp_images,temp_rect = self.load_sprite_sheet('numbers.png',12,1,11,int(11*6/5),-1) self.HI_image = pygame.Surface((22,int(11*6/5))) self.HI_rect = self.HI_image.get_rect() self.HI_image.fill(self.background_col) self.HI_image.blit(temp_images[10],temp_rect) temp_rect.left += temp_rect.width self.HI_image.blit(temp_images[11],temp_rect) self.HI_rect.top = self.height*0.1 self.HI_rect.left = self.width*0.73 def render(self): if pygame.display.get_surface() != None: self.screen.fill(self.background_col) self.new_ground.draw() # clouds.draw(screen) self.scb.draw() if self.high_score != 0: self.highsc.draw() self.screen.blit(self.HI_image,self.HI_rect) self.cacti.draw(self.screen) self.crows.draw(self.screen) self.playerDino.draw() pygame.display.update() def load_sprite_sheet( self, sheetname, nx, ny, scalex = -1, scaley = -1, colorkey = None, ): fullname = os.path.join('sprites_copy',sheetname) sheet = pygame.image.load(fullname) sheet = sheet.convert() sheet_rect = sheet.get_rect() sprites = [] sizex = sheet_rect.width/nx sizey = sheet_rect.height/ny for i in range(0,ny): for j in range(0,nx): rect = pygame.Rect((j*sizex,i*sizey,sizex,sizey)) image = pygame.Surface(rect.size) image = image.convert() image.blit(sheet,(0,0),rect) if colorkey is not None: if colorkey is -1: colorkey = image.get_at((0,0)) image.set_colorkey(colorkey,RLEACCEL) if scalex != -1 or scaley != -1: image = pygame.transform.scale(image,(scalex,scaley)) sprites.append(image) sprite_rect = sprites[0].get_rect() return sprites,sprite_rect def reset(self): self.gamespeed = 4 self.startMenu = False self.gameOver = False self.gameQuit = False self.playerDino = Dino(44,47) self.new_ground = Ground(-1*self.gamespeed) self.scb = Scoreboard() self.highsc = Scoreboard(self.width*0.78) self.counter = 0 self.t_reward = 0 self.crow_height_index = 0 self.nearest = 800 self.second_nearest = 1000 self.action_complete = True self.cacti = pygame.sprite.Group() self.crows = pygame.sprite.Group() self.last_obstacle = pygame.sprite.Group() Cactus.containers = self.cacti Crow.containers = self.crows self.old_states = [] self.new_states = [] self.old_states.append(self.new_ground.speed/-4) self.old_states.append(np.digitize(9.0, self.discrete_spaces)) self.old_states.append(np.digitize(9.0, self.discrete_spaces)) self.old_states.append(self.crow_height_index) # self.old_states.append("Crouch" if self.playerDino.rect[2] != 44 else " standing") self.old_states.append(0 if self.playerDino.rect[2] != 44 else 1) self.play() return np.array(self.old_states, dtype=np.float64) def play(self): for c in self.cacti: c.movement[0] = -1*self.gamespeed if pygame.sprite.collide_mask(self.playerDino,c): self.playerDino.isDead = True for p in self.crows: p.movement[0] = -1*self.gamespeed if pygame.sprite.collide_mask(self.playerDino,p): self.playerDino.isDead = True if len(self.cacti) < 2: if len(self.cacti) == 0: self.last_obstacle.empty() self.last_obstacle.add(Cactus(self.gamespeed,40,40)) else: for l in self.last_obstacle: if l.rect.right < self.width*0.7 and random.randrange(0,200) == 10: self.last_obstacle.empty() self.last_obstacle.add(Cactus(self.gamespeed, 40, 40)) if len(self.crows) == 0 and random.randrange(0,200) == 30 and self.counter == 1: for l in self.last_obstacle: if l.rect.right < self.width*0.7: self.last_obstacle.empty() self.last_obstacle.add(Crow(self.gamespeed, 40, 40)) self.playerDino.update() self.cacti.update() # self.crows.update() self.new_ground.update() self.scb.update(self.playerDino.score) all_loc = [] self.nearest = 1000 self.crow_height_index = 0 for c in self.cacti: if c.rect.left > 80: all_loc.append(c.rect.left) if c.rect.left < self.nearest: self.nearest = c.rect.left for p in self.crows: if p.rect.left > 80: all_loc.append(p.rect.left) if p.rect.left < self.nearest: self.nearest = p.rect.left self.crow_height_index = p.crow_height_index + 1 if len(all_loc) > 1: all_loc.remove(min(all_loc)) self.second_nearest = min(all_loc) else: self.second_nearest += self.playerDino.rect.right # print(nearest - self.playerDino.rect.right, second_nearest - self.playerDino.rect.right) self.new_states = [] self.new_states.append(self.new_ground.speed/-4) # self.new_states.append(np.digitize(self.nearest, self.discrete_spaces)) self.new_states.append(np.digitize(round(self.nearest / self.playerDino.rect.right,2), self.discrete_spaces)) self.new_states.append(np.digitize(round(self.second_nearest / self.playerDino.rect.right,2), self.discrete_spaces)) self.new_states.append(self.crow_height_index) # self.new_states.append("Jump" if self.playerDino.rect[1] != 100 else "running") # self.new_states.append("Crouch" if self.playerDino.rect[2] != 44 else " standing") self.new_states.append(0 if self.playerDino.rect[2] != 44 else 1) if(self.playerDino.rect[1] == 100 and (self.playerDino.rect[2] == 44 or self.playerDino.rect[2] == 59)): self.i = 0 self.action_complete = True if(self.playerDino.rect[1] != 100): self.i += 1 self.highsc.update(self.high_score) if self.allow_rendering: self.render() self.clock.tick(self.FPS) if self.playerDino.isDead: # print('Reward: -1000') # print("final_ states: ", self.new_states) # print("<<<<<<GAME OVER>>>>>>>") self.gameOver = True # self.reset() if self.counter%700 == 699: self.new_ground.speed -= 1 self.gamespeed += 1 self.t_reward += 99 self.counter = (self.counter + 1) def step(self, action): ## 0 - stay, 1 - jump, 2 - crouch, 3 - standup # while not self.gameQuit: # while not self.gameOver: self.t_reward = 0 if True: if action == 0: ## event.key == pygame.K_SPACE self.action_complete = False if self.playerDino.rect.bottom == int(0.98*self.height): self.playerDino.isJumping = True # if pygame.mixer.get_init() != None: # jump_sound.play() self.playerDino.movement[1] = -1*self.playerDino.jumpSpeed # self.t_reward -= 36 while True: self.play() if self.action_complete : self.action_complete = False break if action == 1: ## event.key == pygame.K_DOWN # if not (self.playerDino.isJumping and self.playerDino.isDead): # self.playerDino.isDucking = True self.play() if action == 2: self.playerDino.isDucking = False self.play() if action == 4: self.close() return 0, 0, True else: self.play() self.t_reward += 1 if self.gameOver: self.t_reward -= 101 return np.array(self.new_states), self.t_reward, self.gameOver # self.close() def close(self): pygame.display.quit() pygame.quit() quit()
def run_game(): #初始化循环并创建一个对象 prtips() pygame.init() #设置背景音效 pygame.mixer_music.load('Lullatone - outside sandwiches.mp3') pygame.mixer_music.play(10, 0) #加载动作音效 di_settings = Settings() screen = pygame.display.set_mode( (di_settings.screen_width, di_settings.screen_height)) pygame.display.set_caption('dinosaur run!') #生成对象图片列表 image_d = ['images/long1.png', 'images/long2.png', 'images/long3.png'] image_c = [ 'images/cactus01.png', 'images/cactus02.png', 'images/cactus03.png' ] image_b = ['images/bird1.png', 'images/bird2.png', 'images/bird3.png'] #初始化障碍物-鸟 bird = Bird(800, 150, screen) dino = Dino(screen) dino.load('images/long1_2.png', 40, 43, 2) group = pygame.sprite.Group() group.add(dino) #初始化地图 aa = 0 cc = 0 dd = 0 bg1 = MyMap(0, 0, screen) bg2 = MyMap(734, 0, screen) ca1 = obstacle.Cactus(800, 205, screen) ca2 = obstacle.Cactus(1200, 205, screen) ca3 = obstacle.Cactus(800, 205, screen) #设置一些标志变量 player_jump = 0 jump_vel = -4.95 flag_bird = False flag_cactus1 = -1 flag_cactus2 = -1 flag_cactus3 = -1 a_rate = 10000 rate = 2 #载入结束图像 image_over = pygame.image.load('images/game_over.png').convert_alpha() image_overd = pygame.image.load('images/over.png').convert_alpha() tick = pygame.time.Clock() #开始游戏主循环 while True: tick.tick(100) ticks = pygame.time.get_ticks() #计数器 dd += 1 scoreboard = Scoreboard(di_settings, screen, dd / 10) cc += 1 if int(cc / 10) == 3: cc = 0 # 监视键盘和鼠标事件 for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: player_jump = 1 elif event.key == pygame.K_p: while not event.key == 27: for event in pygame.event.get(): print() elif event.key == 27: sys.exit() else: prtips() if dd == 1050: a_rate = 2100 #绘制背景 bg1.map_update() bg2.map_update() bg1.map_rolling(rate * (1 + dd / a_rate)) bg2.map_rolling(rate * (1 + dd / a_rate)) #是否生成仙人掌 flag_cactus1 = ca1.randcactus(flag_cactus1) flag_cactus2 = ca2.randcactus(flag_cactus2) if (not flag_cactus1 == -1) and dd > 1300: # 绘制仙人掌 ca1.blitme(image_c[flag_cactus1]) flag_cactus1 = ca1.cactus_rolling(flag_cactus1, rate * (1 + dd / a_rate)) if (not flag_cactus2 == -1) and dd > 1300: ca2.blitme(image_c[flag_cactus2]) flag_cactus2 = ca2.cactus_rolling(flag_cactus2, rate * (1 + dd / a_rate)) if dd <= 1000: flag_cactus3 = 2 if flag_cactus3 == 2: ca3.blitme(image_c[flag_cactus3]) flag_cactus3 = ca3.cactus_rolling(flag_cactus3, rate * (1 + dd / a_rate)) #更新恐龙位置 jump_vel, player_jump = dino.jump(player_jump, jump_vel, 1 + dd / a_rate) if player_jump == 0: group.update(ticks) group.draw(screen) else: dino.blitme(image_d[2]) #是否生成飞鸟 if dd == 800: flag_bird = True # 更新飞鸟 if flag_bird: flag_bird = bird.bird_rolling() bird.blitme(image_b[int(cc / 15)]) #更新计分板 scoreboard.show_score() # 更新画面 pygame.display.update() #检测碰撞 hit = hit_find(dino.x, ca1.x, ca2.x, bird.x, dino.y) if hit: break screen.blit(image_over, (270, 100)) screen.blit(image_overd, (220, 140)) pygame.display.update() time.sleep(1)
class Game: def __init__(self): self.reset() def curses_initialize_screen(self): self.stdscr = curses.initscr() curses.noecho() curses.cbreak() self.stdscr.keypad(True) curses.curs_set(0) self.stdscr.border() self.stdscr.nodelay(1) def set_max_dimensions(self): self.rows_max, self.cols_max = self.stdscr.getmaxyx() def initialize_obstacles(self): self.array_obstacles = [ Obstacle(self, self.cols_max - 1, self.ground_level, 2) ] self.next_obstacle_generate_time = 0 def reset(self): self.curses_initialize_screen() self.set_max_dimensions() self.ground_level = self.rows_max - 3 self.ground_string = '=' * (self.cols_max - 3) self.dino = Dino(self) self.score = Score(self.stdscr) self.initialize_obstacles() self.show_loading_animation() def show_loading_animation(self): def draw_multiline_string(s): for y, line in enumerate(s.splitlines(), 2): self.stdscr.addstr(y, 2, line) self.stdscr.refresh() self.stdscr.refresh() self.update() for ascii_number in ascii_numbers: draw_multiline_string(clear_text) draw_multiline_string(ascii_number) time.sleep(1) def handle_key_press(self): k = self.stdscr.getch() if k == curses.ERR: return if k == 27: self.destroy() sys.exit() elif k == 98: self.reset() elif k == 97: self.dino.jump() def draw_obstacles(self): for obstacle in self.array_obstacles: obstacle.draw() def generate_next_obstacle(self): if self.next_obstacle_generate_time - time.time() < 0: self.next_obstacle_generate_time = time.time() + random.randint( 1, 5) self.array_obstacles.append( Obstacle(self, self.cols_max - 1, self.ground_level, random.randint(2, 4))) def draw_ground(self): self.stdscr.addstr(self.ground_level, 3, self.ground_string) def update(self): self.stdscr.erase() self.set_max_dimensions() self.handle_key_press() self.draw_obstacles() self.generate_next_obstacle() self.dino.update() self.score.update() self.draw_ground() self.stdscr.refresh() def destroy(self): self.stdscr.clear() curses.nocbreak() self.stdscr.keypad(False) curses.echo() curses.endwin()
from dino import Dino from cactus import Cactus from ScreenPrinter import ScreenPrinter from pterosaur import Pterosaur from color import colors # from highscorehandler import ServerHandler printer = ScreenPrinter("background.txt", term_dim_x=WINDOW_DIM_X, term_dim_y=WINDOW_DIM_Y) dino_spr = Sprite.fromFilePath("resources/dino/dino.txt") printer.attachSprite(dino_spr) dino = Dino(dino_spr, strength=DINO_STRENGTH, gravity=DINO_GRAVITY, pos_y=WINDOW_DIM_Y - 12, collision_logic=DINO_COLLISION_LOGIC, framerate=DINO_FRAMERATE) cactus_sprites = [] cacti = [] pterosaurs = [] counter = 0 latest = 0 cactus_spacer_float = 50.0 pterosaur_spacer_float = 50.0 speed = 3
from dino import Dino from DQNAgent import DQNAgent import numpy as np import time episodes = 1000 state_size = 4 action_size = 3 # 1. do nothing, 2. jump, 3. lower agent = DQNAgent(state_size, action_size) dino = Dino() scores = [] for e in range(episodes): # restart the game dino.start() state = dino.get_obstacles() state = np.reshape(state, [1, 4]) done = False while not done: state = dino.get_obstacles() state = np.reshape(state, [1, 4]) # decide action action = agent.act(state) if action == 1:
return False return True pygame.init() #inicializando jogo velX = 4 floor = pygame.image.load('chao0.png') back = pygame.image.load('chao4.bmp') #1600 de largura por 600 de altura win = pygame.display.set_mode((CONTS_XWIN, CONTS_YWIN)) win.fill((255, 255, 255)) #fills with wight pygame.display.set_caption("first Game") dino1 = Dino() tempoIni = clock() run = True lista = [] flag = False def drawBackGround(): win.fill((255, 255, 255)) #fills with wight for i in range(0, CONTS_XWIN, 60): win.blit(floor, (i, CONTS_YINI + CONTS_CHARH))
class Agent: def __init__(self, index, debug=False): self.index = index self.debug = debug self.alive_since = None self.died_at = None self.dino = Dino() def setup(self): self.dino.setup() self.driver = webdriver.Chrome(options=options) self.driver.implicitly_wait(10) self.driver.get( 'file:///Users/lukaszskrzeszewski/projects/venv3.7/dinotrainer/trex/index.html' ) self.document = self.driver.find_element(By.XPATH, '//html') def start(self): self.setup() self.alive_since = dt.now() #self.document.send_keys(Keys.SPACE) while self.isDead() == False: self.react() sleep(0.1) if (self.debug == True): print('Agent ', self.index, ' died, score: ', self.score()) return {'score': self.score(), 'index': self.index} def score(self): return (self.died_at - self.alive_since).total_seconds() def isDead(self): if self.died_at == None: if self.driver.execute_script( "return Runner.instance_.crashed") == True: self.died_at = dt.now() return True else: return False else: return True def react(self): X = self.get_data() action = self.dino.react(X) self.__react(action) def get_data(self): self.document.send_keys(Keys.SPACE) screenshot = self.get_screenshot() rhdata = screenshot[60:, 45:450] rhdata = np.where(rhdata > 0, 1, 0) up = rhdata[:25] down = rhdata[25:] up_sum = np.sum(up, axis=0) down_sum = np.sum(down, axis=0) return np.append(up_sum, down_sum).reshape((1, 810)) def __react(self, action): actions = { 'down': lambda: self.document.send_keys(Keys.ARROW_DOWN), 'up': lambda: self.document.send_keys(Keys.SPACE), } print('action', action) callback = actions.get(action, lambda: None) callback() def get_screenshot(self): data = self.driver.execute_script( 'return Runner.instance_.canvasCtx.getImageData(0,0,150,600)' )['data'] #data = self.driver.execute_script('return document.getElementsByClassName("runner-canvas")[0].getContext("2d").getImageData(0,0,600,150);')['data'] #a = np.array(data).reshape((90000, 4)) #a = a[:, 2] a = data[0::4] b = np.reshape(a, (150, 600)) #self.driver.save_screenshot(os.path.join(os.path.dirname(os.path.realpath(__file__)), '.', 'screenshot.png')) save_file = os.path.join(os.getcwd(), "data.png") fig = plt.figure(figsize=(4, 5)) plt.imshow(b, interpolation='nearest') plt.savefig(save_file) plt.close(fig) return b def test(self): data = self.driver.execute_script( 'return document.getElementsByClassName("runner-canvas")[0].getContext("2d").getImageData(0,0,600,150);' )['data'] a = np.array(data).reshape((90000, 4)) a = a[:, 0] b = a.reshape((150, 600)) fig = plt.figure(figsize=(4, 5)) plt.imshow(b, interpolation='nearest') plt.savefig(save_file) plt.close(fig) self.driver.save_screenshot( os.path.join(os.path.dirname(os.path.realpath(__file__)), '.', 'ss.png')) data = self.driver.execute_script( 'return document.getElementsByClassName("runner-canvas")[0].toDataURL("image/png");' ) print('Canvas length: ', data) return b
def __init__(self, index, debug=False): self.index = index self.debug = debug self.alive_since = None self.died_at = None self.dino = Dino()
def __init__(self): self.herd = [ Dino("Raptor", 125, 15), Dino("T-Rex", 125, 15), Dino("Stegosaurus", 125, 15) ]
def gameplay(): global high_score gamespeed = 4 startMenu = False gameOver = False gameQuit = False playerDino = Dino(44,47) new_ground = Ground(-1*gamespeed) scb = Scoreboard() highsc = Scoreboard(width*0.78) counter = 0 cacti = pygame.sprite.Group() pteras = pygame.sprite.Group() clouds = pygame.sprite.Group() last_obstacle = pygame.sprite.Group() Cactus.containers = cacti Ptera.containers = pteras Cloud.containers = clouds retbutton_image,retbutton_rect = load_image('replay_button.png',35,31,-1) gameover_image,gameover_rect = load_image('game_over.png',190,11,-1) temp_images,temp_rect = load_sprite_sheet('numbers.png',12,1,11,int(11*6/5),-1) HI_image = pygame.Surface((22,int(11*6/5))) HI_rect = HI_image.get_rect() HI_image.fill(background_col) HI_image.blit(temp_images[10],temp_rect) temp_rect.left += temp_rect.width HI_image.blit(temp_images[11],temp_rect) HI_rect.top = height*0.1 HI_rect.left = width*0.73 while not gameQuit: while startMenu: pass while not gameOver: if pygame.display.get_surface() == None: print("Couldn't load display surface") gameQuit = True gameOver = True else: for event in pygame.event.get(): if event.type == pygame.QUIT: gameQuit = True gameOver = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: if playerDino.rect.bottom == int(0.98*height): playerDino.isJumping = True if pygame.mixer.get_init() != None: jump_sound.play() playerDino.movement[1] = -1*playerDino.jumpSpeed if event.key == pygame.K_DOWN: if not (playerDino.isJumping and playerDino.isDead): playerDino.isDucking = True if event.type == pygame.KEYUP: if event.key == pygame.K_DOWN: playerDino.isDucking = False for c in cacti: c.movement[0] = -1*gamespeed if pygame.sprite.collide_mask(playerDino,c): playerDino.isDead = True if pygame.mixer.get_init() != None: die_sound.play() for p in pteras: p.movement[0] = -1*gamespeed if pygame.sprite.collide_mask(playerDino,p): playerDino.isDead = True if pygame.mixer.get_init() != None: die_sound.play() if len(cacti) < 2: if len(cacti) == 0: last_obstacle.empty() last_obstacle.add(Cactus(gamespeed,40,40)) else: for l in last_obstacle: if l.rect.right < width*0.7 and random.randrange(0,50) == 10: last_obstacle.empty() last_obstacle.add(Cactus(gamespeed, 40, 40)) if len(pteras) == 0 and random.randrange(0,200) == 10 and counter > 500: for l in last_obstacle: if l.rect.right < width*0.8: last_obstacle.empty() last_obstacle.add(Ptera(gamespeed, 46, 40)) if len(clouds) < 5 and random.randrange(0,300) == 10: Cloud(width,random.randrange(height/5,height/2)) playerDino.update() cacti.update() pteras.update() clouds.update() new_ground.update() scb.update(playerDino.score) highsc.update(high_score) if pygame.display.get_surface() != None: screen.fill(background_col) new_ground.draw(screen) clouds.draw(screen) scb.draw(screen) if high_score != 0: highsc.draw(screen) screen.blit(HI_image,HI_rect) cacti.draw(screen) pteras.draw(screen) playerDino.draw(screen) pygame.display.update() clock.tick(FPS) if playerDino.isDead: gameOver = True if playerDino.score > high_score: high_score = playerDino.score if counter%700 == 699: new_ground.speed -= 1 gamespeed += 1 counter = (counter + 1) if gameQuit: break while gameOver: if pygame.display.get_surface() == None: print("Couldn't load display surface") gameQuit = True gameOver = False else: for event in pygame.event.get(): if event.type == pygame.QUIT: gameQuit = True gameOver = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: gameQuit = True gameOver = False if event.key == pygame.K_RETURN or event.key == pygame.K_SPACE: gameOver = False gameplay() highsc.update(high_score) if pygame.display.get_surface() != None: disp_gameOver_msg(retbutton_image,gameover_image) if high_score != 0: highsc.draw(screen) screen.blit(HI_image,HI_rect) pygame.display.update() clock.tick(FPS) pygame.quit() quit()
class Gym: """'Gym' class: train the AI agent Attributes: 'args' (ArgumentParser): parser gethering all the Game parameters 'dino' (Dino): Dino controller 'highscore' (tuple of int, (human, AI)): the best score achieved by a human and an AI 'isHuman' (bool): whether a human or an AI is playing the game 't' (int): number of time steps since the beginning of the game 'agent' (AIAgent, default=None): AI agent playing the game """ def __init__(self, args): super(Gym).__init__() self.args = args # environment parameters self.dino = Dino(args) # game parameters self.highscore = load_highscore(args.highscore_filename) self.t = 0 # to play with an AI self.isHuman = (args.agent == "human") if not self.isHuman: self.agent = AIAgent(args, self.dino) # load saved parameters if self.args.load_save: load_agent(self.agent, self.args.save_filename) # listen to user inputs self.inputs_list = [] threading.Thread(target=input_thread, args=(self.inputs_list, )).start() def step(self): """Play one time step in the game. """ # take an action self.agent.choose_action() # feed the transition information to the agent self.agent.set_transition() # update the number of time steps self.t += 1 def play(self): """Play games continuously. """ # display command info display_info(self.dino.get_n_sim(), self.highscore, self.args.commands_filename) handle_user_command(self) # start the first game self.dino.start() while True: # check if the game is not failed if not self.dino.is_crashed(): if not self.isHuman: # check if the game is not paused if not self.dino.is_playing() and self.args.play_bg: self.dino.game.resume() # take a step if the AI is playing if self.dino.is_playing(): self.step() # otherwise launch a new game else: # reset the number of steps self.t = 0 # current score score = self.dino.get_score() # check if the highscore is beaten human_score = max(score * self.isHuman, self.highscore[0]) ai_score = max(score * (not self.isHuman), self.highscore[1]) # update the highscore self.highscore = (human_score, ai_score) update_score(self.highscore, self.args.highscore_filename) # display command info display_info(self.dino.get_n_sim(), self.highscore, self.args.commands_filename) handle_user_command(self) if not self.isHuman: # save the last simulation self.agent.reset() else: self.dino.start()