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
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 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()
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 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 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()
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)