python实现滑雪游戏


Posted in Python onFebruary 22, 2020

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

# coding: utf-8
# 滑雪小游戏
import sys
import pygame
import random
from pygame.locals import *
 
 
# 滑雪者类
class SkierClass(pygame.sprite.Sprite):
 def __init__(self):
 pygame.sprite.Sprite.__init__(self)
 # 滑雪者的朝向(-2到2)
 self.direction = 0
 self.imgs = ["./images/skier_forward.png", "./images/skier_right1.png", "./images/skier_right2.png", "./images/skier_left2.png", "./images/skier_left1.png"]
 self.person = pygame.image.load(self.imgs[self.direction])
 self.rect = self.person.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.person = pygame.image.load(self.imgs[self.direction])
 self.rect = self.person.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)
 
 
# 障碍物类
# 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 create_obstacles(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(["tree", "flag"])
 img_path = './images/tree.png' if attribute=="tree" else './images/flag.png'
 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 Show_Start_Interface(Demo, width, height):
 Demo.fill((255, 255, 255))
 tfont = pygame.font.Font('./font/simkai.ttf', width//4)
 cfont = pygame.font.Font('./font/simkai.ttf', width//20)
 title = tfont.render(u'滑雪游戏', True, (255, 0, 0))
 content = cfont.render(u'按任意键开始游戏', True, (0, 0, 255))
 trect = title.get_rect()
 trect.midtop = (width/2, height/10)
 crect = content.get_rect()
 crect.midtop = (width/2, height/2.2)
 Demo.blit(title, trect)
 Demo.blit(content, crect)
 pygame.display.update()
 while True:
 for event in pygame.event.get():
 if event.type == QUIT:
 sys.exit()
 elif event.type == pygame.KEYDOWN:
 return
 
 
# 主程序
def main():
 '''
 初始化
 '''
 pygame.init()
 # 声音
 pygame.mixer.init()
 pygame.mixer.music.load("./music/bg_music.mp3")
 pygame.mixer.music.set_volume(0.4)
 pygame.mixer.music.play(-1)
 # 屏幕
 screen = pygame.display.set_mode([640, 640])
 pygame.display.set_caption('滑雪游戏-公众号:Charles的皮卡丘')
 # 主频
 clock = pygame.time.Clock()
 # 滑雪者
 skier = SkierClass()
 # 记录滑雪的距离
 distance = 0
 # 创建障碍物
 obstacles0 = create_obstacles(20, 29)
 obstacles1 = create_obstacles(10, 19)
 obstaclesflag = 0
 obstacles = AddObstacles(obstacles0, obstacles1)
 # 分数
 font = pygame.font.Font(None, 50)
 score = 0
 score_text = font.render("Score: "+str(score), 1, (0, 0, 0))
 # 速度
 speed = [0, 6]
 Show_Start_Interface(screen, 640, 640)
 '''
 主循环
 '''
 # 更新屏幕
 def update():
 screen.fill([255, 255, 255])
 pygame.display.update(obstacles.draw(screen))
 screen.blit(skier.person, skier.rect)
 screen.blit(score_text, [10, 10])
 pygame.display.flip()
 
 while True:
 # 左右键控制人物方向
 for event in pygame.event.get():
 if event.type == 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 = create_obstacles(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 = create_obstacles(10, 19)
 obstacles = AddObstacles(obstacles0, obstacles1)
 # 用于碰撞检测
 for obstacle in obstacles:
 obstacle.move(distance)
 # 碰撞检测
 is_hit = pygame.sprite.spritecollide(skier, obstacles, False)
 if is_hit:
 if is_hit[0].attribute == "tree" and not is_hit[0].passed:
 score -= 50
 skier.person = pygame.image.load("./images/skier_fall.png")
 update()
 # 摔倒后暂停一会再站起来
 pygame.time.delay(1000)
 skier.person = pygame.image.load("./images/skier_forward.png")
 skier.direction = 0
 speed = [0, 6]
 is_hit[0].passed = True
 elif is_hit[0].attribute == "flag" and not is_hit[0].passed:
 score += 10
 obstacles.remove(is_hit[0])
 score_text = font.render("Score: "+str(score), 1, (0, 0, 0))
 update()
 clock.tick(40)
 
 
if __name__ == '__main__':
 main()

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

Python 相关文章推荐
python实现模拟按键,自动翻页看u17漫画
Mar 17 Python
Python psutil模块简单使用实例
Apr 28 Python
python实现JAVA源代码从ANSI到UTF-8的批量转换方法
Aug 10 Python
python实现识别相似图片小结
Feb 22 Python
python递归删除指定目录及其所有内容的方法
Jan 13 Python
Windows下将Python文件打包成.EXE可执行文件的方法
Aug 03 Python
用python实现k近邻算法的示例代码
Sep 06 Python
使用python绘制3维正态分布图的方法
Dec 29 Python
原来我一直安装 Python 库的姿势都不对呀
Nov 11 Python
PyQt5实现画布小程序
May 30 Python
Python爬虫小例子——爬取51job发布的工作职位
Jul 10 Python
pytho matplotlib工具栏源码探析一之禁用工具栏、默认工具栏和工具栏管理器三种模式的差异
Feb 25 Python
Python实现栈的方法详解【基于数组和单链表两种方法】
Feb 22 #Python
Python栈的实现方法示例【列表、单链表】
Feb 22 #Python
python实现滑雪者小游戏
Feb 22 #Python
python实现拼图小游戏
Feb 22 #Python
Python双链表原理与实现方法详解
Feb 22 #Python
Python单链表原理与实现方法详解
Feb 22 #Python
python函数enumerate,operator和Counter使用技巧实例小结
Feb 22 #Python
You might like
php查看session内容的函数
2008/08/27 PHP
PHP中去掉字符串首尾空格的方法
2012/05/19 PHP
一个简单至极的PHP缓存类代码
2015/10/23 PHP
Laravel 5.4因特殊字段太长导致migrations报错的解决
2017/10/22 PHP
Laravel Eloquent分表方法并使用模型关联的实现
2019/11/25 PHP
解决JS中乘法的浮点错误的方法
2014/01/03 Javascript
什么是MEAN?JavaScript编程中的MEAN是什么意思?
2014/12/18 Javascript
JavaScript比较两个对象是否相等的方法
2015/02/06 Javascript
javascript日期操作详解(脚本之家整理)
2015/09/05 Javascript
jQuery实现为控件添加水印文字效果(附源码)
2015/12/02 Javascript
谈谈我对JavaScript原型和闭包系列理解(随手笔记8)
2015/12/24 Javascript
jQuery查找节点并获取节点属性的方法
2016/09/09 Javascript
移动端滑动插件Swipe教程
2016/10/16 Javascript
node.js学习之base64编码解码
2016/10/21 Javascript
JS实现旋转木马式图片轮播效果
2017/01/18 Javascript
手把手教你使用vue-cli脚手架(图文解析)
2017/11/08 Javascript
Nuxt.js开启SSR渲染的教程详解
2018/11/30 Javascript
微信小程序实现动态获取元素宽高的方法分析
2018/12/10 Javascript
Angular封装搜索框组件操作示例
2019/04/25 Javascript
js中调用微信的扫描二维码功能的实现代码
2020/04/11 Javascript
VUE 实现element upload上传图片到阿里云
2020/08/12 Javascript
在Python中利用Into包整洁地进行数据迁移的教程
2015/03/30 Python
浅谈Python NLP入门教程
2017/12/25 Python
python3实现跳一跳点击跳跃
2018/01/08 Python
pandas.dataframe按行索引表达式选取方法
2018/10/30 Python
基于python实现对文件进行切分行
2020/04/26 Python
解决pymysql cursor.fetchall() 获取不到数据的问题
2020/05/15 Python
纯CSS3大转盘抽奖示例代码(响应式、可配置)
2017/01/13 HTML / CSS
雅萌 (YA-MAN) :日本美容家电领域的龙头企业
2017/05/12 全球购物
三月雷锋月活动总结
2014/07/03 职场文书
大学生国庆节65周年演讲稿范文
2014/09/25 职场文书
社区四风存在问题及整改措施
2014/10/26 职场文书
golang实现一个简单的websocket聊天室功能
2021/10/05 Golang
JavaScript 事件捕获冒泡与捕获详情
2021/11/11 Javascript
Python OpenCV实现图像模板匹配详解
2022/04/07 Python
Docker与K8s关系介绍不会Docker也可以使用K8s
2022/06/25 Servers