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文件和目录操作详解
Feb 08 Python
python实现指定字符串补全空格的方法
Apr 30 Python
再谈Python中的字符串与字符编码(推荐)
Dec 14 Python
python+mongodb数据抓取详细介绍
Oct 25 Python
Python将DataFrame的某一列作为index的方法
Apr 08 Python
无法使用pip命令安装python第三方库的原因及解决方法
Jun 12 Python
python中hasattr()、getattr()、setattr()函数的使用
Aug 16 Python
VS2019+python3.7+opencv4.1+tensorflow1.13配置详解
Apr 16 Python
Python闭包与装饰器原理及实例解析
Apr 30 Python
python实现逻辑回归的示例
Oct 09 Python
python3访问字典里的值实例方法
Nov 18 Python
Python利用socket模块开发简单的端口扫描工具的实现
Jan 27 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
可以在线执行PHP代码包装修正版
2008/03/15 PHP
php getimagesize 上传图片的长度和宽度检测代码
2010/05/15 PHP
解析PHP实现多进程并行执行脚本
2013/06/18 PHP
php几个预定义变量$_SERVER用法小结
2014/11/07 PHP
Laravel 5.5官方推荐的Nginx配置学习教程
2017/10/06 PHP
js中document.getElementByid、document.all和document.layers区分介绍
2011/12/08 Javascript
JavaScript实现统计文本框Textarea字数增强用户体验
2012/12/21 Javascript
密码强度检测效果实现原理与代码
2013/01/04 Javascript
脚本合并提升javascript性能示例
2014/02/24 Javascript
jquery图片轮播插件仿支付宝2013版全屏图片幻灯片
2014/04/03 Javascript
JavaScript创建对象的方式小结(4种方式)
2015/12/17 Javascript
JS实现类似百叶窗下拉菜单效果
2016/12/30 Javascript
vue全局组件与局部组件使用方法详解
2018/03/29 Javascript
vue.js动画中的js钩子函数的实现
2018/07/06 Javascript
微信小程序事件流原理解析
2019/11/27 Javascript
使用Python保存网页上的图片或者保存页面为截图
2016/03/05 Python
Python导入模块时遇到的错误分析
2017/08/30 Python
Python Tkinter实现简易计算器功能
2018/01/30 Python
Pyspider中给爬虫伪造随机请求头的实例
2018/05/07 Python
Python抽象和自定义类定义与用法示例
2018/08/23 Python
Mac下Anaconda的安装和使用教程
2018/11/29 Python
python实现图像拼接功能
2020/03/23 Python
python collections模块的使用
2020/10/16 Python
Python下载的11种姿势(小结)
2020/11/18 Python
纯CSS3实现的8种Loading动画效果
2014/07/05 HTML / CSS
意大利在线大学图书馆:Libreria universitaria
2019/07/16 全球购物
abstract class和interface有什么区别?
2012/01/03 面试题
模具设计与制造专业应届生求职信
2013/10/18 职场文书
竞聘副主任科员演讲稿
2014/01/11 职场文书
安全生产一岗双责责任书
2014/07/28 职场文书
房屋买卖授权委托书
2014/09/27 职场文书
2014年纪检部工作总结
2014/11/12 职场文书
丧事主持词
2015/07/02 职场文书
小学秋季运动会通讯稿
2015/11/25 职场文书
python自动化测试之Selenium详解
2022/03/13 Python
Netflix《海贼王》真人版剧集多张片场照曝光
2022/04/04 日漫