小言_互联网的博客

python--谷歌恐龙快跑小项目

485人阅读  评论(0)

用300行代码左右实现谷歌休闲的恐龙快跑游戏!

主函数:

import sys
import math
import time
import random
import pygame
from pygame.locals import *
from Scene import Scene
from Obstacle import Plant, Ptera
from Dinosaur import Dinosaur

# 定义背景填充色,画布宽和高
BACKGROUND = (250, 250, 250)
WIDTH = 800
HEIGHT = 400

#定义游戏结束界面是的样式,即对两张图片的位置显示
def show_gameover(screen):
    screen.fill(BACKGROUND)
    gameover_img = pygame.image.load('./images/others/gameover.png').convert_alpha()
    gameover_rect = gameover_img.get_rect()
    gameover_rect.left, gameover_rect.top = WIDTH//3, int(HEIGHT/2.4)
    screen.blit(gameover_img, gameover_rect)
    restart_img = pygame.image.load('./images/others/restart.png').convert_alpha()
    restart_rect = restart_img.get_rect()
    restart_rect.left, restart_rect.top = int(WIDTH/2.25), int(HEIGHT/2)
    screen.blit(restart_img, restart_rect)
    pygame.display.update()
    # 鼠标精准点击重新开始图标以执行重新开始游戏功能
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                sys.exit()
                pygame.quit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                if mouse_pos[0] < restart_rect.right and mouse_pos[0] > restart_rect.left and\
                    mouse_pos[1] < restart_rect.bottom and mouse_pos[1] > restart_rect.top:
                    return True

#将Score转为生成障碍物的概率,e的-score次幂
def sigmoid(score):
    probability = 1 / (1 + math.exp(-score))
    return min(probability, 0.6)

#主函数
def main():
    # 初始化
    pygame.init()
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    pygame.display.set_caption("dragon running")
    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('./font/font1.ttf', 20)
    # 实例化
    dinosaur = Dinosaur(WIDTH, HEIGHT)
    scene = Scene(WIDTH, HEIGHT)
    plants = pygame.sprite.Group()
    pteras = pygame.sprite.Group()
    # 产生障碍物事件
    # 设置的定时器常量第一个用pygame.USEREVENT第二个用pygame.USEREVENT+1
    GenPlantEvent = pygame.constants.USEREVENT + 0
    pygame.time.set_timer(GenPlantEvent, 1500)
    GenPteraEvent = pygame.constants.USEREVENT + 1
    pygame.time.set_timer(GenPteraEvent, 5000)
    # 游戏是否结束了
    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 > 10:
                    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


#run
if __name__ == '__main__':
    res = True
    while res:
        res = main()

实现主要事件,恐龙的跳跃,奔跑,表情的变换,地图背景的滑动,障碍物的出现(仙人掌和飞鸟),音乐和音效的设置等等

恐龙类:


  
  1. import pygame
  2. '''恐龙类'''
  3. class Dinosaur(pygame.sprite.Sprite):
  4. def __init__( self, WIDTH=640, HEIGHT=500):
  5. pygame.sprite.Sprite.__init__(self)
  6. self.HEIGHT = HEIGHT
  7. self.WIDTH = WIDTH
  8. # self.imgs = ['./images/dinosaur/wait.png', './images/dinosaur/afraid.png', './images/dinosaur/running.png', './images/dinosaur/flying.png']
  9. self.imgs = [ './images/dinosaur/dino.png', './images/dinosaur/dino_ducking.png']
  10. self.reset()
  11. '''跳跃'''
  12. def jump( self, time_passed):
  13. # time_passed很小时,可近似为匀速运动
  14. if self.is_jumping_up:
  15. self.rect.top -= self.jump_v * time_passed
  16. self.jump_v = max( 0, self.jump_v - self.jump_a_up * time_passed)
  17. if self.jump_v == 0:
  18. self.is_jumping_up = False
  19. else:
  20. self.rect.top = min(self.initial_top, self.rect.top + self.jump_v * time_passed)
  21. self.jump_v += self.jump_a_down * time_passed
  22. if self.rect.top == self.initial_top:
  23. self.is_jumping = False
  24. self.is_jumping_up = True
  25. self.jump_v = self.jump_v0
  26. '''跳跃时变为感到恐惧的表情'''
  27. def be_afraid( self):
  28. self.dinosaur = self.dinosaurs.subsurface(( 352, 0), ( 88, 95))
  29. '''把自己画到屏幕上去'''
  30. def draw( self, screen):
  31. if self.is_running and not self.is_jumping:
  32. self.running_count += 1
  33. if self.running_count == 6:
  34. self.running_count = 0
  35. self.running_flag = not self.running_flag
  36. if self.running_flag:
  37. self.dinosaur = self.dinosaurs.subsurface(( 176, 0), ( 88, 95))
  38. else:
  39. self.dinosaur = self.dinosaurs.subsurface(( 264, 0), ( 88, 95))
  40. screen.blit(self.dinosaur, self.rect)
  41. '''重置'''
  42. def reset( self):
  43. # 恐龙是否在奔跑
  44. self.is_running = False
  45. # 为了奔跑特效
  46. self.running_flag = False
  47. self.running_count = 0
  48. # 恐龙是否在跳跃
  49. self.is_jumping = False
  50. # 恐龙是否在向上跳跃
  51. self.is_jumping_up = True
  52. # 跳跃初始速度
  53. self.jump_v0 = 500
  54. # 跳跃瞬时速度
  55. self.jump_v = self.jump_v0
  56. # 跳跃加速度
  57. self.jump_a_up = 1000
  58. self.jump_a_down = 800
  59. # 小恐龙初始位置
  60. self.initial_left = 40
  61. self.initial_top = int(self.HEIGHT/ 2.3)
  62. self.dinosaurs = pygame.image.load(self.imgs[ 0]).convert_alpha()
  63. self.dinosaur = self.dinosaurs.subsurface(( 0, 0), ( 88, 95))
  64. self.rect = self.dinosaur.get_rect()
  65. self.rect.left, self.rect.top = self.initial_left, self.initial_top

背景画布:


  
  1. import pygame
  2. import random
  3. '''场景类'''
  4. class Scene(pygame.sprite.Sprite):
  5. def __init__( self, WIDTH=640, HEIGHT=500):
  6. pygame.sprite.Sprite.__init__(self)
  7. self.WIDTH = WIDTH
  8. self.HEIGHT = HEIGHT
  9. self.speed = 5
  10. self.imgs = [ './images/bg/bg1.png', './images/bg/bg2.png', './images/bg/bg3.png']
  11. self.reset()
  12. '''不停向左移动'''
  13. def move( self):
  14. self.x = self.x - self.speed
  15. '''把自己画到屏幕上去'''
  16. def draw( self, screen):
  17. if self.bg1_rect.right < 0:
  18. self.x = 0
  19. self.bg1 = self.bg2
  20. self.bg1_rect = self.bg2_rect
  21. self.bg2 = self.bg3
  22. self.bg2_rect = self.bg3_rect
  23. self.bg3 = pygame.image.load(self.imgs[random.randint( 0, 2)]).convert_alpha()
  24. self.bg3_rect = self.bg3.get_rect()
  25. self.bg1_rect.left, self.bg1_rect.top = self.x, int(self.HEIGHT/ 2.3)
  26. self.bg2_rect.left, self.bg2_rect.top = self.bg1_rect.right, int(self.HEIGHT/ 2.3)
  27. self.bg3_rect.left, self.bg3_rect.top = self.bg2_rect.right, int(self.HEIGHT/ 2.3)
  28. screen.blit(self.bg1, self.bg1_rect)
  29. screen.blit(self.bg2, self.bg2_rect)
  30. screen.blit(self.bg3, self.bg3_rect)
  31. '''重置'''
  32. def reset( self):
  33. self.x = 0
  34. self.bg1 = pygame.image.load(self.imgs[ 0]).convert_alpha()
  35. self.bg2 = pygame.image.load(self.imgs[ 1]).convert_alpha()
  36. self.bg3 = pygame.image.load(self.imgs[ 2]).convert_alpha()
  37. self.bg1_rect = self.bg1.get_rect()
  38. self.bg2_rect = self.bg2.get_rect()
  39. self.bg3_rect = self.bg3.get_rect()
  40. self.bg1_rect.left, self.bg1_rect.top = self.x, int(self.HEIGHT/ 2.3)
  41. self.bg2_rect.left, self.bg2_rect.top = self.bg1_rect.right, int(self.HEIGHT/ 2.3)
  42. self.bg3_rect.left, self.bg3_rect.top = self.bg2_rect.right, int(self.HEIGHT/ 2.3)

障碍物类:


  
  1. import random
  2. import pygame
  3. '''植物'''
  4. class Plant(pygame.sprite.Sprite):
  5. def __init__( self, WIDTH=640, HEIGHT=500):
  6. pygame.sprite.Sprite.__init__(self)
  7. self.WIDTH = WIDTH
  8. self.HEIGHT = HEIGHT
  9. # 统计分数时用的
  10. self.added_score = False
  11. self.speed = 5
  12. # self.imgs = ['./images/obstacles/plant1.png', './images/obstacles/plant2.png', './images/obstacles/plant3.png', './images/obstacles/plant4.png']
  13. self.imgs = [ './images/obstacles/plant_big.png', './images/obstacles/plant_small.png']
  14. self.generate_random()
  15. '''随机生成障碍物'''
  16. def generate_random( self):
  17. idx = random.randint( 0, 1)
  18. temp = pygame.image.load(self.imgs[idx]).convert_alpha()
  19. if idx == 0:
  20. self.plant = temp.subsurface(( 101*random.randint( 0, 2), 0), ( 101, 101))
  21. else:
  22. self.plant = temp.subsurface(( 68*random.randint( 0, 2), 0), ( 68, 70))
  23. self.rect = self.plant.get_rect()
  24. self.rect.left, self.rect.top = self.WIDTH+ 60, int(self.HEIGHT/ 2)
  25. '''不停往左移动'''
  26. def move( self):
  27. self.rect.left = self.rect.left-self.speed
  28. '''把自己画到屏幕上去'''
  29. def draw( self, screen):
  30. screen.blit(self.plant, self.rect)
  31. '''飞龙'''
  32. class Ptera(pygame.sprite.Sprite):
  33. def __init__( self, WIDTH=640, HEIGHT=500):
  34. pygame.sprite.Sprite.__init__(self)
  35. self.WIDTH = WIDTH
  36. self.HEIGHT = HEIGHT
  37. # 统计分数时用的
  38. self.added_score = False
  39. self.imgs = [ './images/obstacles/ptera.png']
  40. # 为了飞行特效
  41. self.flying_count = 0
  42. self.flying_flag = True
  43. # 统计分数时用的
  44. self.speed = 7
  45. self.generate()
  46. '''生成飞龙'''
  47. def generate( self):
  48. self.ptera = pygame.image.load(self.imgs[ 0]).convert_alpha()
  49. self.ptera_0 = self.ptera.subsurface(( 0, 0), ( 92, 81))
  50. self.ptera_1 = self.ptera.subsurface(( 92, 0), ( 92, 81))
  51. self.rect = self.ptera_0.get_rect()
  52. self.rect.left, self.rect.top = self.WIDTH+ 30, int(self.HEIGHT/ 20)
  53. '''不停往左移动'''
  54. def move( self):
  55. self.rect.left = self.rect.left-self.speed
  56. '''把自己画到屏幕上去'''
  57. def draw( self, screen):
  58. self.flying_count += 1
  59. if self.flying_count % 6 == 0:
  60. self.flying_flag = not self.flying_flag
  61. if self.flying_flag:
  62. screen.blit(self.ptera_0, self.rect)
  63. else:
  64. screen.blit(self.ptera_1, self.rect)

截图如下:

 


转载:https://blog.csdn.net/Abtxr/article/details/127872056
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场