Exemplo n.º 1
0
import pygame

from settings import Settings
from landscape import Landscape
from dinosaur import Dinosaur

pygame.init()
canvas = pygame.display.set_mode(Settings.screen_size)

landscape = Landscape(canvas)
dinosaur = Dinosaur(canvas, landscape)

clock = pygame.time.Clock()

done = False
while not done:
    canvas.fill((0, 0, 0))
    landscape.draw()
    dinosaur.draw()
    pygame.display.flip()
    landscape.update()
    clock.tick(10)
Exemplo n.º 2
0
def main():
    # 初始化
    pygame.init()
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    pygame.display.set_caption("Dinosaur Game Race")
    clock = pygame.time.Clock()
    # 得分
    score = 0
    # 加载一些素材
    ##	jump_sound = pygame.mixer.Sound("./music/jump.wav")
    ##	jump_sound.set_volume(6)
    ##	die_sound = pygame.mixer.Sound("./music/die.wav")
    ##	die_sound.set_volume(6)
    ##	pygame.mixer.init()
    ##	pygame.mixer.music.load("./music/bg_music.mp3")
    ##	pygame.mixer.music.set_volume(0.6)
    ##	pygame.mixer.music.play(-1)
    font = pygame.font.Font('/Users/wanyiyang/Desktop/pygame/simkai.ttf', 20)
    # 实例化
    dinosaur = Dinosaur(WIDTH, HEIGHT)
    scene = Scene(WIDTH, HEIGHT)
    plants = pygame.sprite.Group()
    pteras = pygame.sprite.Group()
    # 产生障碍物事件
    GenPlantEvent = pygame.constants.USEREVENT + 0
    pygame.time.set_timer(GenPlantEvent, 4500)
    GenPteraEvent = pygame.constants.USEREVENT + 1
    pygame.time.set_timer(GenPteraEvent, 15000)
    # 游戏是否结束了
    running = True
    # 是否可以产生障碍物flag
    flag_plant = False
    flag_ptera = False
    t0 = time.time()
    # 主循环
    while running:
        for event in pygame.event.get():
            if event.type == QUIT:
                sys.exit()
                pygame.quit()
            if event.type == GenPlantEvent:
                flag_plant = True
            if event.type == GenPteraEvent:
                if score > 50:
                    flag_ptera = True
        key_pressed = pygame.key.get_pressed()
        if key_pressed[pygame.K_SPACE]:
            dinosaur.is_jumping = True


##			jump_sound.play()
        screen.fill(BACKGROUND)
        time_passed = time.time() - t0
        t0 = time.time()
        # 场景
        scene.move()
        scene.draw(screen)
        # 小恐龙
        dinosaur.is_running = True
        if dinosaur.is_jumping:
            dinosaur.be_afraid()
            dinosaur.jump(time_passed)
        dinosaur.draw(screen)
        # 障碍物-植物
        if random.random() < sigmoid(score) and flag_plant:
            plant = Plant(WIDTH, HEIGHT)
            plants.add(plant)
            flag_plant = False
        for plant in plants:
            plant.move()
            if dinosaur.rect.left > plant.rect.right and not plant.added_score:
                score += 1
                plant.added_score = True
            if plant.rect.right < 0:
                plants.remove(plant)
                continue
            plant.draw(screen)
        # 障碍物-飞龙
        if random.random() < sigmoid(score) and flag_ptera:
            if len(pteras) > 1:
                continue
            ptera = Ptera(WIDTH, HEIGHT)
            pteras.add(ptera)
            flag_ptera = False
        for ptera in pteras:
            ptera.move()
            if dinosaur.rect.left > ptera.rect.right and not ptera.added_score:
                score += 5
                ptera.added_score = True
            if ptera.rect.right < 0:
                pteras.remove(ptera)
                continue
            ptera.draw(screen)
        # 碰撞检测
        if pygame.sprite.spritecollide(dinosaur, plants,
                                       False) or pygame.sprite.spritecollide(
                                           dinosaur, pteras, False):
            ##			die_sound.play()
            running = False
        # 显示得分
        score_text = font.render("Score: " + str(score), 1, (0, 0, 0))
        screen.blit(score_text, [10, 10])
        pygame.display.flip()
        clock.tick(60)
    res = show_gameover(screen)
    return res
Exemplo n.º 3
0
class Game():

    global jumpCount, isJump

    def __init__(self):
        self.dinosaur = Dinosaur(win, 500 - 100, 450)
        self.bg_colour = win.fill((255, 255, 255))
        self.cactuses = [Cactus(win, 1000), Cactus(win, 1000)]
        self.bg = pygame.image.load("imgs/floor.png")
        self.timer = time.time()
        self.score = -1

    def main(self):
        isJump = False
        jumpCount = 10
        clock = pygame.time.Clock()
        score = 0
        while True:

            clock.tick(60)
            #gen cactuses
            if time.time() - self.timer >= random.randrange(1, 40):
                self.timer = time.time()
                self.cactuses.append(Cactus(win, 1000))
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()

            keys = pygame.key.get_pressed()

            if not (isJump):  # Checks is user is not jumping
                if keys[pygame.K_SPACE]:
                    isJump = True
            else:
                # This is what will happen if we are jumping
                if jumpCount >= -10:
                    self.dinosaur.y -= (jumpCount * abs(jumpCount) / 5) * 1
                    jumpCount -= 0.5
                else:  # This will execute if our jump is finished
                    jumpCount = 10
                    isJump = False
                    # Resetting our Variables
            # del cactuses off of screen
            for cactus in self.cactuses:
                if cactus.x < -84:
                    self.cactuses.remove(cactus)
            # Check for collision between dinosaur and cactus
            for cactus in self.cactuses:
                if cactus.collision(self.dinosaur, win):
                    return False
            self.draw()
            pygame.display.update()

    def draw(self):
        """
        draw all objects onto screen
        """
        STAT_FONT = pygame.font.SysFont("comicsans", 50)
        self.bg_colour = win.fill((255, 255, 255))
        win.blit(self.bg, (0, 480))
        self.dinosaur.draw()
        score_label = STAT_FONT.render("Score: " + str(self.score), 1,
                                       (0, 0, 0))
        win.blit(score_label, (700 - score_label.get_width() - 15, 10))

        for cactus in self.cactuses:
            cactus.draw()
            cactus.move()
            if not cactus.passed and cactus.x < self.dinosaur.x:
                print(self.score)
                self.score += 1
                cactus.passed = True
Exemplo n.º 4
0
    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
    yPos += 1 #increment by 1
Exemplo n.º 5
0
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