Python实现滑雪小游戏


Posted in Python onSeptember 25, 2021

本文实例为大家分享了Python实现滑雪小游戏的具体代码,供大家参考,具体内容如下

Python实现滑雪小游戏

源码分享:

import sys
import cfg
import pygame
import random
 
 
'''滑雪者类'''
class SkierClass(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        # 滑雪者的朝向(-2到2)
        self.direction = 0
        self.imagepaths = cfg.SKIER_IMAGE_PATHS[:-1]
        self.image = pygame.image.load(self.imagepaths[self.direction])
        self.rect = self.image.get_rect()
        self.rect.center = [320, 100]
        self.speed = [self.direction, 6-abs(self.direction)*2]
    '''改变滑雪者的朝向. 负数为向左,正数为向右,0为向前'''
    def turn(self, num):
        self.direction += num
        self.direction = max(-2, self.direction)
        self.direction = min(2, self.direction)
        center = self.rect.center
        self.image = pygame.image.load(self.imagepaths[self.direction])
        self.rect = self.image.get_rect()
        self.rect.center = center
        self.speed = [self.direction, 6-abs(self.direction)*2]
        return self.speed
    '''移动滑雪者'''
    def move(self):
        self.rect.centerx += self.speed[0]
        self.rect.centerx = max(20, self.rect.centerx)
        self.rect.centerx = min(620, self.rect.centerx)
    '''设置为摔倒状态'''
    def setFall(self):
        self.image = pygame.image.load(cfg.SKIER_IMAGE_PATHS[-1])
    '''设置为站立状态'''
    def setForward(self):
        self.direction = 0
        self.image = pygame.image.load(self.imagepaths[self.direction])
 
 
'''
Function:
    障碍物类
Input:
    img_path: 障碍物图片路径
    location: 障碍物位置
    attribute: 障碍物类别属性
'''
class ObstacleClass(pygame.sprite.Sprite):
    def __init__(self, img_path, location, attribute):
        pygame.sprite.Sprite.__init__(self)
        self.img_path = img_path
        self.image = pygame.image.load(self.img_path)
        self.location = location
        self.rect = self.image.get_rect()
        self.rect.center = self.location
        self.attribute = attribute
        self.passed = False
    '''移动'''
    def move(self, num):
        self.rect.centery = self.location[1] - num
 
 
'''创建障碍物'''
def createObstacles(s, e, num=10):
    obstacles = pygame.sprite.Group()
    locations = []
    for i in range(num):
        row = random.randint(s, e)
        col = random.randint(0, 9)
        location  = [col*64+20, row*64+20]
        if location not in locations:
            locations.append(location)
            attribute = random.choice(list(cfg.OBSTACLE_PATHS.keys()))
            img_path = cfg.OBSTACLE_PATHS[attribute]
            obstacle = ObstacleClass(img_path, location, attribute)
            obstacles.add(obstacle)
    return obstacles
 
 
'''合并障碍物'''
def AddObstacles(obstacles0, obstacles1):
    obstacles = pygame.sprite.Group()
    for obstacle in obstacles0:
        obstacles.add(obstacle)
    for obstacle in obstacles1:
        obstacles.add(obstacle)
    return obstacles
 
 
'''显示游戏开始界面'''
def ShowStartInterface(screen, screensize):
    screen.fill((255, 255, 255))
    tfont = pygame.font.Font(cfg.FONTPATH, screensize[0]//5)
    cfont = pygame.font.Font(cfg.FONTPATH, screensize[0]//20)
    title = tfont.render(u'滑雪游戏', True, (255, 0, 0))
    content = cfont.render(u'按任意键开始游戏', True, (0, 0, 255))
    trect = title.get_rect()
    trect.midtop = (screensize[0]/2, screensize[1]/5)
    crect = content.get_rect()
    crect.midtop = (screensize[0]/2, screensize[1]/2)
    screen.blit(title, trect)
    screen.blit(content, crect)
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                return
        pygame.display.update()
 
 
'''显示分数'''
def showScore(screen, score, pos=(10, 10)):
    font = pygame.font.Font(cfg.FONTPATH, 30)
    score_text = font.render("Score: %s" % score, True, (0, 0, 0))
    screen.blit(score_text, pos)
 
 
'''更新当前帧的游戏画面'''
def updateFrame(screen, obstacles, skier, score):
    screen.fill((255, 255, 255))
    obstacles.draw(screen)
    screen.blit(skier.image, skier.rect)
    showScore(screen, score)
    pygame.display.update()
 
 
'''主程序'''
def main():
    # 游戏初始化
    pygame.init()
    pygame.mixer.init()
    pygame.mixer.music.load(cfg.BGMPATH)
    pygame.mixer.music.set_volume(0.4)
    pygame.mixer.music.play(-1)
    # 设置屏幕
    screen = pygame.display.set_mode(cfg.SCREENSIZE)
    pygame.display.set_caption('滑雪游戏 —— 九歌')
    # 游戏开始界面
    ShowStartInterface(screen, cfg.SCREENSIZE)
    # 实例化游戏精灵
    # --滑雪者
    skier = SkierClass()
    # --创建障碍物
    obstacles0 = createObstacles(20, 29)
    obstacles1 = createObstacles(10, 19)
    obstaclesflag = 0
    obstacles = AddObstacles(obstacles0, obstacles1)
    # 游戏clock
    clock = pygame.time.Clock()
    # 记录滑雪的距离
    distance = 0
    # 记录当前的分数
    score = 0
    # 记录当前的速度
    speed = [0, 6]
    # 游戏主循环
    while True:
        # --事件捕获
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT or event.key == pygame.K_a:
                    speed = skier.turn(-1)
                elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:
                    speed = skier.turn(1)
        # --更新当前游戏帧的数据
        skier.move()
        distance += speed[1]
        if distance >= 640 and obstaclesflag == 0:
            obstaclesflag = 1
            obstacles0 = createObstacles(20, 29)
            obstacles = AddObstacles(obstacles0, obstacles1)
        if distance >= 1280 and obstaclesflag == 1:
            obstaclesflag = 0
            distance -= 1280
            for obstacle in obstacles0:
                obstacle.location[1] = obstacle.location[1] - 1280
            obstacles1 = createObstacles(10, 19)
            obstacles = AddObstacles(obstacles0, obstacles1)
        for obstacle in obstacles:
            obstacle.move(distance)
        # --碰撞检测
        hitted_obstacles = pygame.sprite.spritecollide(skier, obstacles, False)
        if hitted_obstacles:
            if hitted_obstacles[0].attribute == "tree" and not hitted_obstacles[0].passed:
                score -= 50
                skier.setFall()
                updateFrame(screen, obstacles, skier, score)
                pygame.time.delay(1000)
                skier.setForward()
                speed = [0, 6]
                hitted_obstacles[0].passed = True
            elif hitted_obstacles[0].attribute == "flag" and not hitted_obstacles[0].passed:
                score += 10
                obstacles.remove(hitted_obstacles[0])
        # --更新屏幕
        updateFrame(screen, obstacles, skier, score)
        clock.tick(cfg.FPS)
 
 
'''run'''
if __name__ == '__main__':
    main();

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python基础教程之元组操作使用详解
Mar 25 Python
深入Python解释器理解Python中的字节码
Apr 01 Python
在Python中使用poplib模块收取邮件的教程
Apr 29 Python
python抽象基类用法实例分析
Jun 04 Python
python中从str中提取元素到list以及将list转换为str的方法
Jun 26 Python
python函数装饰器之带参数的函数和带参数的装饰器用法示例
Nov 06 Python
Python浮点数四舍五入问题的分析与解决方法
Nov 19 Python
Python实现剪刀石头布小游戏(与电脑对战)
Dec 31 Python
Python中import导入不同目录的模块方法详解
Feb 18 Python
Tensorflow使用Anaconda、pycharm安装记录
Jul 29 Python
Python爬虫之Selenium多窗口切换的实现
Dec 04 Python
python 离散点图画法的实现
Apr 01 Python
利用python实时刷新基金估值(摸鱼小工具)
Sep 15 #Python
Python极值整数的边界探讨分析
Sep 15 #Python
Python办公自动化PPT批量转换操作
Sep 15 #Python
Python办公自动化解决world文件批量转换
Sep 15 #Python
Python函数式编程中itertools模块详解
Sep 15 #Python
Python编程中Python与GIL互斥锁关系作用分析
Sep 15 #Python
Python3.10的一些新特性原理分析
Sep 15 #Python
You might like
elgg 获取文件图标地址的方法
2010/03/20 PHP
php自动给网址加上链接的方法
2015/06/02 PHP
微信获取用户地理位置信息的原理与步骤
2015/11/12 PHP
twig模板获取全局变量的方法
2016/02/05 PHP
php微信公众号开发之二级菜单
2018/10/20 PHP
Array.slice()与Array.splice()的返回值类型
2006/10/09 Javascript
Javascript Global对象
2009/08/13 Javascript
jQuery基础知识filter()和find()实例说明
2010/07/06 Javascript
设置jsf的选择框h:selectOneMenu为不可编辑状态的方法
2014/01/07 Javascript
javascript 回到顶部效果的实现代码
2014/02/17 Javascript
深入理解Javascript中的自执行匿名函数
2016/06/03 Javascript
javascript 内置对象及常见API详细介绍
2016/11/01 Javascript
jQuery的三种bind/One/Live/On事件绑定使用方法
2017/02/23 Javascript
js实现倒计时效果(小于10补零)
2017/03/08 Javascript
ReactNative踩坑之配置调试端口的解决方法
2017/07/28 Javascript
AngularJS基于http请求实现下载php生成的excel文件功能示例
2018/01/23 Javascript
浅谈开发eslint规则
2018/10/01 Javascript
vue使用websocket的方法实例分析
2019/06/22 Javascript
ES6实现图片切换特效代码
2020/01/14 Javascript
js实现单元格拖拽效果
2020/02/10 Javascript
vue中实现图片压缩 file文件的方法
2020/05/28 Javascript
机器学习的框架偏向于Python的13个原因
2017/12/07 Python
用pandas中的DataFrame时选取行或列的方法
2018/07/11 Python
对Tensorflow中的矩阵运算函数详解
2018/07/27 Python
python查找指定文件夹下所有文件并按修改时间倒序排列的方法
2018/10/21 Python
详解python中sort排序使用
2019/03/23 Python
通过python 执行 nohup 不生效的解决
2020/04/16 Python
html5-websocket基于远程方法调用的数据交互实现
2012/12/04 HTML / CSS
html5超简单的localStorage实现记住密码的功能实现
2017/09/07 HTML / CSS
领班岗位职责范文
2014/02/06 职场文书
《白鹅》教学反思
2014/04/13 职场文书
汉语言文学毕业求职信
2014/07/17 职场文书
2015年管理人员工作总结
2015/05/13 职场文书
编写python程序的90条建议
2021/04/14 Python
Golang解析JSON对象
2022/04/30 Golang
深入理解MySQL中MVCC与BufferPool缓存机制
2022/05/25 MySQL