首页 > 其他 > 详细

Pygame游戏开发入门(1)-开发框架

时间:2019-04-27 00:48:11      阅读:220      评论:0      收藏:0      [点我收藏+]

pygame库的安装 pip install pygame

pygame最小开发框架

#Pygame Hello World Game
import pygame,sys #引入pygame和sys(python标准库)

pygame.init() #初始化模块创建及变量及设置,默认调用
screen = pygame.display.set_mode((600,400)) #初始化显示窗口,元祖值为宽高
pygame.display.set_caption("Python游戏之旅") #窗体标题设置
#获取事件并逐类响应
while True:      #无限循环,直到python运行时退出结束
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()      #游戏退出
    pygame.display.update() #刷新屏幕

 最小开发框架图示:

技术分享图片

 

壁球小游戏(展示型)与图像的基本使用

1)壁球:游戏需要一个壁球,通过图片引入(小球图片位置:https://python123.io/PY15/PYG02-ball.gif)

2)壁球运动:壁球要能够上下左右移动

3)壁球反弹:壁球要能够在上下左右边缘反弹

笛卡尔坐标系图示:

技术分享图片

 反弹:

与边缘垂直的速度改为反方向运动即 S=-S

壁球小游戏(展示型)代码:

import pygame,sys

pygame.init()
size = width,hight = 600,400
speed = [1,1]
BLACK = 0,0,0
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Pygame壁球")  
ball = pygame.image.load("PYG02-ball.gif") #将()中路径下的图像载入游戏,支持jpg、png、gif等13种常见格式
ballrect = ball.get_rect()#pygame使用内部定义的Surface对象表示所有载入的图像,.get_rect()方法返回一个覆盖图像的矩形Rect对象

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
    ballrect = ballrect.move(speed[0],speed[1])
    if ballrect.left < 0 or ballrect.right > width:
        speed[0] = -speed[0]
    if ballrect.top < 0 or ballrect.bottom > hight:
        speed[1] = -speed[1]

    screen.fill(BLACK)
    screen.blit(ball,ballrect)
    pygame .display.update()

 

ball = pygame.image.load("PYG02-ball.gif")

#将()中路径下的图像载入游戏,支持jpg、png、gif等13种常见格式

 

ballrect = ball.get_rect()

#pygame使用内部定义的Surface对象表示所有载入的图像,.get_rect()方法返回一个覆盖图像的矩形Rect对象

技术分享图片

Rect对象

Rect对象有一些重要属性,例如:

top,bottom,left,right表示上下左右

width,height表示宽度、高度

技术分享图片

 

ballrect.move(x,y)

矩形移动一个偏移量(x,y),即在横轴方向移动x像素,纵轴方向移动y像素,xy为整数

 

if ballrect.left < 0 or ballrect.right > width:
        speed[0] = -speed[0]
    if ballrect.top < 0 or ballrect.bottom > hight:
        speed[1] = -speed[1]

遇到左右两侧,横向速度取反;

遇到上下两侧,纵向速度取反;

 

screen.fill(color)

显示窗口背景填充为color的颜色,采用RGB色彩体系。由于壁球在不断运动,

运动后原有位置将默认填充白色,因此要不断刷新背景色

 

screen.blit(src,dest)

将一个图像绘制在另一个图像上,即将src绘制到dest位置上。通过Rect对象一道对壁球的绘制。

(让图像跟着矩形移动而移动)

 

 

 

 

 

 

 

 

 

 

本文为博主学习笔记,转载需注明来源;

学习视频所属:中国大学MOOC 北京理工大学 嵩天 黄天羽老师https://www.icourse163.org/course/BIT-1001873001


Pygame游戏开发入门(1)-开发框架

原文:https://www.cnblogs.com/cpg123/p/10769766.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!