class Game: def __init__(self): self.bump_audio = BUMP_AUDIO self.over_img = OVER_IMG self.init_game() def init_game(self): # 游戏结束 self.over = False # 创建滚动地图对象 self.bg = RollBackground() # 创建恐龙对象 self.dinosaur = Dinosaur() # 创建障碍物组合 self.obstacles = ObstacleGroup() def process_event(self): for event in pygame.event.get(): if event.type == QUIT: sys.exit(0) elif event.type == KEYDOWN and event.key == K_SPACE: if self.over: self.init_game() else: self.dinosaur.jump() def start(self): while True: self.process_event() if not self.over: self.update_window() if self.dinosaur.collide(self.obstacles): self.over = True self.game_over() self.dinosaur.show_score() pygame.display.update() set_fps(30) def update_window(self): self.bg.update() self.dinosaur.update() self.obstacles.update() def game_over(self): self.bump_audio.play() x = (SCREEN_WIDTH - self.over_img.get_width()) // 2 y = (SCREEN_HEIGHT - self.over_img.get_height()) // 2 SCREEN.blit(self.over_img, (x, y))
def run_game(): pygame.init() dino_settings = Settings() screen = pygame.display.set_mode((dino_settings.screen_width, dino_settings.screen_height)) pygame.display.set_caption("dino") score = float(0) while True: ground = Ground(dino_settings, screen) dinosaur = Dinosaur(dino_settings, screen) clouds = Group() birds = Group() cactus = Group() gf.create_clouds(dino_settings, screen, clouds) gf.create_birds(dino_settings, screen, birds) gf.create_cactus(dino_settings, screen, cactus) sb = Scoreboard(dino_settings, screen) while not dinosaur.dead: gf.check_events(dinosaur) ground.update() dinosaur.update() score += 3 dino_settings.score = int(score) sb.prep_score() gf.update_clouds(dino_settings, screen, clouds) gf.update_birds(dino_settings, screen, birds, dinosaur) gf.update_cactus(dino_settings, screen, cactus, dinosaur) gf.update_screen(dino_settings, screen, ground, clouds, dinosaur, cactus, birds, sb) while dinosaur.dead: exit_game = False for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: mouse_x, mouse_y = pygame.mouse.get_pos() if button.rect.collidepoint(mouse_x, mouse_y): exit_game = True if exit_game: if dino_settings.score > dino_settings.high_score: dino_settings.high_score = dino_settings.score sb.prep_high_score() dino_settings.score = 0 score = 0 break button = Button(dino_settings, screen) button.blitme() pygame.display.flip()
class Game: BLACK = (0, 0, 0) def __init__(self): pygame.display.set_caption('Dinosaur Game') self.clock = pygame.time.Clock() self.height = 400 self.width = 700 self.screen_res = [self.width, self.height] self.screen = pygame.display.set_mode(self.screen_res, pygame.HWSURFACE, 32) self.white = [222, 222, 222] self.black = [0, 0, 0] self.screen.fill(self.white) self.font = pygame.font.SysFont("Calibri", 16) self.ground_y = 250 self.end = False self.obj_speed = 2.5 self.dinosaur = Dinosaur(self) self.cactus_group = pygame.sprite.Group() self.collide = False self.object_period = 5 self.current_obj = None self.score = 0 self.add_speed = 5 self.current_cloud = None while not self.end: self.loop() def loop(self): self.event_loop() self.draw() pygame.display.update() self.clock.tick(60) def event_loop(self): for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN: if event.key == pygame.K_ESCAPE: pygame.quit() sys.exit() def draw(self): self.screen.fill(self.white) self.draw_line() self.draw_dinosaur() self.draw_objects() self.draw_cloud() self.print_score() def draw_line(self): pygame.draw.aaline(self.screen, self.black, (0, self.ground_y), (self.width, self.ground_y)) def print_score(self): font = pygame.font.SysFont(None, 30) text = font.render('Score: ' + str(self.score), True, self.BLACK) self.screen.blit(text, (0, 0)) def draw_dinosaur(self): keys = pygame.key.get_pressed() if not self.dinosaur.is_jumping: if keys[pygame.K_SPACE]: self.dinosaur.is_jumping = True self.dinosaur.direction = 'up' if self.dinosaur.is_jumping: if self.dinosaur.direction == 'up': self.dinosaur.move_up() if self.dinosaur.check_reached_top(): self.dinosaur.direction = 'down' self.dinosaur.set_speed_zero() if self.dinosaur.direction == 'down': self.dinosaur.move_down() if self.dinosaur.check_reached_down(): self.dinosaur.direction = 'up' self.dinosaur.reset_speed() self.dinosaur.is_jumping = False self.dinosaur.update() def create_object(self): self.update_object_speed() random_number = random.randrange(2) if random_number == 0: collide_object = Cactus(self) else: collide_object = Bird(self) return collide_object def init_objects(self): if self.current_obj: if self.current_obj.x < self.get_appear_position(): self.current_obj = self.create_object() self.score += 1 else: self.current_obj = self.create_object() def update_object_speed(self): if self.score % self.add_speed == 0: self.obj_speed += 0.3 def draw_objects(self): self.init_objects() self.current_obj.check_collide() if self.collide: self.end = True else: self.current_obj.move() self.current_obj.update() def draw_cloud(self): if self.current_cloud is None: self.current_cloud = Cloud(self) else: if self.current_cloud.check_passed() and random.randint(1, 4) != 1: self.current_cloud = Cloud(self) self.current_cloud.update() @staticmethod def get_appear_position(): return 2 * random.randrange(-5, 5)
t = pygame.time.get_ticks() #Get current time deltaTime = (t-lastFrame)/1000.0 #Find difference in time and then convert it to seconds lastFrame = t #set lastFrame as the current time for next frame. for event in pygame.event.get(): #Check for events if event.type == pygame.QUIT: pygame.quit() #quits quit() if event.type == pygame.KEYDOWN: #If user uses the keyboard if event.key == pygame.K_SPACE: #If that key is space dinosaur.jump() #Make dinosaur jump gameDisplay.fill(black) dinosaur.update(deltaTime) dinosaur.draw(gameDisplay) for obs in obstacles: obs.update(deltaTime, VELOCITY) obs.draw(gameDisplay) if(obs.checkOver()): lastObstacle += MINGAP+(MAXGAP-MINGAP)*random.random() obs.x = lastObstacle lastObstacle -= VELOCITY*deltaTime pygame.draw.rect(gameDisplay,white, [0,GROUND_HEIGHT, width, height-GROUND_HEIGHT]) pygame.draw.rect(gameDisplay, white, [xPos,yPos,40,50]) #make xPos the value of pygame xPos += 1 #increment by 1
if event.type == ADDCLOUD: if random.randint(0, 10) > 5: new_cloud = Cloud() clouds.add(new_cloud) all_sprites.add(new_cloud) # object update pressed_keys = pygame.key.get_pressed() # Update if pygame.sprite.spritecollideany(contact, trees): dinosaur.die() elif pygame.sprite.spritecollideany(contact, birds): dinosaur.die() else: grounds.update() dinosaur.update(pressed_keys) contact.update(dinosaur.rect.center[0], dinosaur.rect.bottom, dinosaur.squat) trees.update() birds.update() clouds.update() # screen update screen.fill((255, 255, 255)) # screen blit # screen.blit(dinosaur.surf, dinosaur.rect) for entity in all_sprites: screen.blit(entity.surf, entity.rect) pygame.display.flip() # update screen
class SnapStrats: """Overall class to manage game assests and behaviours""" def __init__(self): """Initilize the game, and create game resources""" pygame.init() self.settings = Settings() self.screen = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height)) pygame.display.set_caption("Snap Strats") self.dinosaur = Dinosaur(self) self.car = Car(self) self.dinosaurs = pygame.sprite.Group() self._create_fleet() def _create_fleet(self): """Create the cars""" # Create an alien and find the number of aliens in a rrow. dinosaur = Dinosaur(self) dinosaur_height = dinosaur.rect.height available_space_y = self.settings.screen_height - (2 * dinosaur_height) number_dinosaurs_y = available_space_y // (2 * dinosaur_height) # Create the first row of dino saurs for dinosaur_number in range(number_dinosaurs_y): dinosaur = Dinosaur(self) dinosaur.y = dinosaur_height + 2 * dinosaur_height * dinosaur_number dinosaur.rect.y = dinosaur.y self.dinosaurs.add(dinosaur) def run_game(self): """Start the main loop for the game.""" while True: self._check_events() self.car.update() self.dinosaur.update() self._update_screen() self._update_dinosaurs() # Watch for keyboard and mouse events. def _update_dinosaurs(self): """Update the position of the dinosaurs""" self._check_fleet_edges() self.dinosaurs.update() def _check_fleet_edges(self): """Respoind appropriately if any dinosauars have reached the edgee""" for dino in self.dinosaurs.sprites(): if dino.check_edges(): self._change_fleet_direction() break def _change_fleet_direction(self): """Drop the entire fleet and change the fleets direction""" self.settings.fleet_direction *= -1 def _check_events(self): """Respond to keypresses and mouse events.""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame.KEYUP: self._check_keyup_events(event) def _check_keydown_events(self, event): """Responds to keypresses""" if event.key == pygame.K_RIGHT: self.car.moving_right = True elif event.key == pygame.K_LEFT: self.car.moving_left = True elif event.key == pygame.K_UP: self.car.moving_forward = True elif event.key == pygame.K_DOWN: self.car.moving_backwards = True elif event.key == pygame.K_q: sys.exit() def _check_keyup_events(self, event): """Responds to key releases""" if event.key == pygame.K_RIGHT: self.car.moving_right = False elif event.key == pygame.K_LEFT: self.car.moving_left = False elif event.key == pygame.K_UP: self.car.moving_forward = False elif event.key == pygame.K_DOWN: self.car.moving_backwards = False def _update_screen(self): """Update images on the screen, and flip to the new screen.""" self.screen.blit(self.settings.bg_image, (0, 0)) self.car.blitme() self.dinosaurs.draw(self.screen) # pygame.display.flip()
class Game: """ 游戏 """ def __init__(self, screen): """ 初始化 """ self._screen = screen # 屏幕画面 self._gameState = GameState.start # 游戏状态 0:开始画面; 1:游戏中; 2:游戏结束 self._frameCount = 0 # 每个游戏状态的帧数计数 self._score = Score(self) # 分数系统 # 游戏元素 self._startScene = StartScene() self._gameoverScene = GameoverScene(self) self._dinosaur = Dinosaur(self) self._cactusGroup = pygame.sprite.RenderPlain() self._birdGroup = pygame.sprite.RenderPlain() self._terrian = Terrian(self) self._cloudGroup = pygame.sprite.RenderPlain() self._moon = Moon(self) self._starGroup = pygame.sprite.RenderPlain() # 控制难度的变量 self._lastEnemyFrameCount = 0 # 上一次出现敌人的帧数计数 self._curEnemeyProbability = Settings.enemyInitProbability # x,当前每帧敌人出现的概率为1/x self._curEnemyMinFrameInterval = Settings.enemyInitMinFrameInterval # 当前敌人最小帧数间隔 self._curTerrianSpeed = Settings.terrianInitSpeed # 当前地形移动速度 # 控制环境的变量 self._lastCloudFrameCount = Settings.cloudFrameInterval # 上一次出现云的帧数计数 self._isDay = True # 是否白天 self._dayNightFrame = Settings.dayNightChangeFrame # 自从白天/黑夜开始的帧数,初始值不为0,因为开始无需昼夜交替 @property def curShowScore(self): """ 获取当前展示分数 """ return self._score.curShowScore @property def curTerrianSpeed(self): """ 获取当前地形移动速度 """ return self._curTerrianSpeed def showNightImage(self): """ 是否显示夜晚图像 """ if self._isDay: return self._dayNightFrame < Settings.dayNightChangeFrame - Settings.dayToNightChangeColorFrame return self._dayNightFrame >= Settings.dayToNightChangeColorFrame def handleEvents(self): """ 处理事件 """ self._frameCount += 1 for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if self._gameState == GameState.start: if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: self._gameState = GameState.running self._frameCount = 0 elif self._gameState == GameState.running: if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: self._dinosaur.startUp() elif event.key == pygame.K_DOWN: self._dinosaur.startDown() elif event.key == pygame.K_UP: self._dinosaur.startUp() elif event.type == pygame.KEYUP: if event.key == pygame.K_DOWN: self._dinosaur.endDown() elif event.key in (pygame.K_SPACE, pygame.K_UP): self._dinosaur.endUp() else: if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: if self._frameCount >= Settings.restartMinFrameCount: self._restart() def updateAndDraw(self): """ 更新并绘制 """ def update(): """ 更新游戏元素和状态 """ self._terrian.update() self._updateClouds() self._moon.update() self._updateStars() self._updateEnemies() self._dinosaur.update() self._score.addScore(self._curTerrianSpeed) self._updateDayNight() self._updateDifficulty() def showGameScene(): """ 显示当前帧 """ colorValue = round( 255 * min(self._dayNightFrame / Settings.dayNightChangeFrame, 1)) if not self._isDay: colorValue = 255 - colorValue self._screen.fill(rect=self._screen.get_rect(), color=(colorValue, colorValue, colorValue)) if not self._isDay and self._dayNightFrame > Settings.dayToNightMoonShowFrame: self._starGroup.draw(self._screen) self._moon.draw(self._screen) self._terrian.draw(self._screen) self._cloudGroup.draw(self._screen) self._cactusGroup.draw(self._screen) self._birdGroup.draw(self._screen) self._dinosaur.draw(self._screen) self._score.draw(self._screen) def handleCollision(): """ 处理碰撞 """ if self._detectCollision(): self._dinosaur.die() self._gameState = GameState.gameover self._frameCount = 0 if self._gameState == GameState.start: self._startScene.draw(self._screen) elif self._gameState == GameState.running: update() showGameScene() handleCollision() else: if self._frameCount <= 1: # 只需显示一次 showGameScene() self._gameoverScene.draw(self._screen) pygame.display.update() def _updateEnemies(self): """ 更新敌人 """ self._cactusGroup.update() for cactus in self._cactusGroup.copy(): if cactus.rect.right < 0: self._cactusGroup.remove(cactus) self._birdGroup.update() for bird in self._birdGroup.copy(): if bird.rect.right < 0: self._birdGroup.remove(bird) self._lastEnemyFrameCount += 1 if self._lastEnemyFrameCount > self._curEnemyMinFrameInterval and\ (random.randint(0, round(self._curEnemeyProbability)) == 0 or self._lastEnemyFrameCount >= self._curEnemeyProbability): if self.curShowScore < Settings.birdScore or random.randint( 0, 2) <= 1: self._cactusGroup.add(Cactus(self)) else: self._birdGroup.add(Bird(self)) self._lastEnemyFrameCount = 0 def _updateClouds(self): """ 更新云群 """ self._cloudGroup.update() for cloud in self._cloudGroup.copy(): if cloud.rect.right < 0: self._cloudGroup.remove(cloud) self._lastCloudFrameCount += 1 if self._lastCloudFrameCount > Settings.cloudFrameInterval and\ random.randint(0, Settings.cloudProbability) == 0: self._cloudGroup.add(Cloud(self)) self._lastCloudFrameCount = 0 def _updateStars(self): """ 更新星群 """ self._starGroup.update() for star in self._starGroup.copy(): if star.rect.right < 0: self._starGroup.remove(star) if random.randint(0, Settings.starProbability) == 0: self._starGroup.add(Star(self)) def _updateDayNight(self): """ 更新日夜状态 """ curIsDay = (self.curShowScore < Settings.dayNightScore) or\ (self.curShowScore % Settings.dayNightScore > Settings.nightScore) if curIsDay == self._isDay: self._dayNightFrame += 1 else: self._isDay = curIsDay self._dayNightFrame = max( Settings.dayNightChangeFrame - self._dayNightFrame, 0) if curIsDay: self._moon.nextPhase() def _updateDifficulty(self): """ 更新难度参数 """ self._curEnemeyProbability = Settings.enemyInitProbability +\ (Settings.enemyMaxProbability - Settings.enemyInitProbability) /\ Settings.maxDifficultyScore * self.curShowScore self._curEnemeyProbability = max(self._curEnemeyProbability, Settings.enemyMaxProbability) self._curEnemyMinFrameInterval = Settings.enemyInitMinFrameInterval +\ (Settings.enemyMinMinFrameInterval - Settings.enemyInitMinFrameInterval) /\ Settings.maxDifficultyScore * self.curShowScore self._curEnemyMinFrameInterval = max(self._curEnemyMinFrameInterval, Settings.enemyMinMinFrameInterval) self._curTerrianSpeed = Settings.terrianInitSpeed +\ (Settings.terrianMaxSpeed - Settings.terrianInitSpeed) / Settings.maxDifficultyScore * self.curShowScore self._curTerrianSpeed = min(self._curTerrianSpeed, Settings.terrianMaxSpeed) def _detectCollision(self) -> bool: """ 检测碰撞 """ return pygame.sprite.spritecollide(self._dinosaur, self._cactusGroup, False, pygame.sprite.collide_mask) or\ pygame.sprite.spritecollide(self._dinosaur, self._birdGroup, False, pygame.sprite.collide_mask) def _restart(self): """ 重开游戏 """ self._gameState = GameState.running self._frameCount = 0 self._score.setScore(0) self._dinosaur.restart() self._cactusGroup.empty() self._birdGroup.empty() self._lastEnemyFrameCount = 0 self._curEnemeyProbability = Settings.enemyInitProbability self._curEnemyMinFrameInterval = Settings.enemyInitMinFrameInterval self._curTerrianSpeed = Settings.terrianInitSpeed