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

Posted DY.memory

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python--谷歌恐龙快跑小项目相关的知识,希望对你有一定的参考价值。

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

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

恐龙类:


import pygame


'''恐龙类'''
class Dinosaur(pygame.sprite.Sprite):
	def __init__(self, WIDTH=640, HEIGHT=500):
		pygame.sprite.Sprite.__init__(self)
		self.HEIGHT = HEIGHT
		self.WIDTH = WIDTH
		# self.imgs = ['./images/dinosaur/wait.png', './images/dinosaur/afraid.png', './images/dinosaur/running.png', './images/dinosaur/flying.png']
		self.imgs = ['./images/dinosaur/dino.png', './images/dinosaur/dino_ducking.png']
		self.reset()
	'''跳跃'''
	def jump(self, time_passed):
		# time_passed很小时,可近似为匀速运动
		if self.is_jumping_up:
			self.rect.top -= self.jump_v * time_passed
			self.jump_v = max(0, self.jump_v - self.jump_a_up * time_passed)
			if self.jump_v == 0:
				self.is_jumping_up = False
		else:
			self.rect.top = min(self.initial_top, self.rect.top + self.jump_v * time_passed)
			self.jump_v += self.jump_a_down * time_passed
			if self.rect.top == self.initial_top:
				self.is_jumping = False
				self.is_jumping_up = True
				self.jump_v = self.jump_v0
	'''跳跃时变为感到恐惧的表情'''
	def be_afraid(self):
		self.dinosaur = self.dinosaurs.subsurface((352, 0), (88, 95))
	'''把自己画到屏幕上去'''
	def draw(self, screen):
		if self.is_running and not self.is_jumping:
			self.running_count += 1
			if self.running_count == 6:
				self.running_count = 0
				self.running_flag = not self.running_flag
			if self.running_flag:
				self.dinosaur = self.dinosaurs.subsurface((176, 0), (88, 95))
			else:
				self.dinosaur = self.dinosaurs.subsurface((264, 0), (88, 95))
		screen.blit(self.dinosaur, self.rect)
	'''重置'''
	def reset(self):
		# 恐龙是否在奔跑
		self.is_running = False
		# 为了奔跑特效
		self.running_flag = False
		self.running_count = 0
		# 恐龙是否在跳跃
		self.is_jumping = False
		# 恐龙是否在向上跳跃
		self.is_jumping_up = True
		# 跳跃初始速度
		self.jump_v0 = 500
		# 跳跃瞬时速度
		self.jump_v = self.jump_v0
		# 跳跃加速度
		self.jump_a_up = 1000
		self.jump_a_down = 800
		# 小恐龙初始位置
		self.initial_left = 40
		self.initial_top = int(self.HEIGHT/2.3)
		self.dinosaurs = pygame.image.load(self.imgs[0]).convert_alpha()
		self.dinosaur = self.dinosaurs.subsurface((0, 0), (88, 95))
		self.rect = self.dinosaur.get_rect()
		self.rect.left, self.rect.top = self.initial_left, self.initial_top

背景画布:

import pygame
import random

'''场景类'''
class Scene(pygame.sprite.Sprite):
	def __init__(self, WIDTH=640, HEIGHT=500):
		pygame.sprite.Sprite.__init__(self)
		self.WIDTH = WIDTH
		self.HEIGHT = HEIGHT
		self.speed = 5
		self.imgs = ['./images/bg/bg1.png', './images/bg/bg2.png', './images/bg/bg3.png']
		self.reset()
	'''不停向左移动'''
	def move(self):
		self.x = self.x - self.speed
	'''把自己画到屏幕上去'''
	def draw(self, screen):
		if self.bg1_rect.right < 0:
			self.x = 0
			self.bg1 = self.bg2
			self.bg1_rect = self.bg2_rect
			self.bg2 = self.bg3
			self.bg2_rect = self.bg3_rect
			self.bg3 = pygame.image.load(self.imgs[random.randint(0, 2)]).convert_alpha()
			self.bg3_rect = self.bg3.get_rect()
		self.bg1_rect.left, self.bg1_rect.top = self.x, int(self.HEIGHT/2.3)
		self.bg2_rect.left, self.bg2_rect.top = self.bg1_rect.right, int(self.HEIGHT/2.3)
		self.bg3_rect.left, self.bg3_rect.top = self.bg2_rect.right, int(self.HEIGHT/2.3)
		screen.blit(self.bg1, self.bg1_rect)
		screen.blit(self.bg2, self.bg2_rect)
		screen.blit(self.bg3, self.bg3_rect)
	'''重置'''
	def reset(self):
		self.x = 0
		self.bg1 = pygame.image.load(self.imgs[0]).convert_alpha()
		self.bg2 = pygame.image.load(self.imgs[1]).convert_alpha()
		self.bg3 = pygame.image.load(self.imgs[2]).convert_alpha()
		self.bg1_rect = self.bg1.get_rect()
		self.bg2_rect = self.bg2.get_rect()
		self.bg3_rect = self.bg3.get_rect()
		self.bg1_rect.left, self.bg1_rect.top = self.x, int(self.HEIGHT/2.3)
		self.bg2_rect.left, self.bg2_rect.top = self.bg1_rect.right, int(self.HEIGHT/2.3)
		self.bg3_rect.left, self.bg3_rect.top = self.bg2_rect.right, int(self.HEIGHT/2.3)

障碍物类:


import random
import pygame


'''植物'''
class Plant(pygame.sprite.Sprite):
	def __init__(self, WIDTH=640, HEIGHT=500):
		pygame.sprite.Sprite.__init__(self)
		self.WIDTH = WIDTH
		self.HEIGHT = HEIGHT
		# 统计分数时用的
		self.added_score = False
		self.speed = 5
		# self.imgs = ['./images/obstacles/plant1.png', './images/obstacles/plant2.png', './images/obstacles/plant3.png', './images/obstacles/plant4.png']
		self.imgs = ['./images/obstacles/plant_big.png', './images/obstacles/plant_small.png']
		self.generate_random()
	'''随机生成障碍物'''
	def generate_random(self):
		idx = random.randint(0, 1)
		temp = pygame.image.load(self.imgs[idx]).convert_alpha()
		if idx == 0:
			self.plant = temp.subsurface((101*random.randint(0, 2), 0), (101, 101))
		else:
			self.plant = temp.subsurface((68*random.randint(0, 2), 0), (68, 70))
		self.rect = self.plant.get_rect()
		self.rect.left, self.rect.top = self.WIDTH+60, int(self.HEIGHT/2)
	'''不停往左移动'''
	def move(self):
		self.rect.left = self.rect.left-self.speed
	'''把自己画到屏幕上去'''
	def draw(self, screen):
		screen.blit(self.plant, self.rect)


'''飞龙'''
class Ptera(pygame.sprite.Sprite):
	def __init__(self, WIDTH=640, HEIGHT=500):
		pygame.sprite.Sprite.__init__(self)
		self.WIDTH = WIDTH
		self.HEIGHT = HEIGHT
		# 统计分数时用的
		self.added_score = False
		self.imgs = ['./images/obstacles/ptera.png']
		# 为了飞行特效
		self.flying_count = 0
		self.flying_flag = True
		# 统计分数时用的
		self.speed = 7
		self.generate()
	'''生成飞龙'''
	def generate(self):
		self.ptera = pygame.image.load(self.imgs[0]).convert_alpha()
		self.ptera_0 = self.ptera.subsurface((0, 0), (92, 81))
		self.ptera_1 = self.ptera.subsurface((92, 0), (92, 81))
		self.rect = self.ptera_0.get_rect()
		self.rect.left, self.rect.top = self.WIDTH+30, int(self.HEIGHT/20)
	'''不停往左移动'''
	def move(self):
		self.rect.left = self.rect.left-self.speed
	'''把自己画到屏幕上去'''
	def draw(self, screen):
		self.flying_count += 1
		if self.flying_count % 6 == 0:
			self.flying_flag = not self.flying_flag
		if self.flying_flag:
			screen.blit(self.ptera_0, self.rect)
		else:
			screen.blit(self.ptera_1, self.rect)

截图如下:

 

以上是关于python--谷歌恐龙快跑小项目的主要内容,如果未能解决你的问题,请参考以下文章

教程 | 强化学习训练Chrome小恐龙Dino Run:最高超过4000分

小侄女画的小恐龙VS我用Python画的小恐龙,你更加喜欢谁的!

python实现“跳跃的恐龙”这款游戏

51nod 1765 谷歌的恐龙

flutter开发游戏入门(仿谷歌浏览器小恐龙Chrome dino)二

使用 Python 开发一个恐龙跑跑小游戏,玩起来