首页 > 编程语言 >Python13章

Python13章

时间:2022-12-02 23:00:34浏览次数:32  
标签:ball 窗口 ballrect Python13 pygame speed event

实验13:Pygame游戏编程

一、实验目的和要求

二、实验环境

Python 3.10 64_bit

三、实验过程

1、实例1:制作一个跳跃的小球游戏

(1)代码如下:

 1 # -*- coding:utf-8 -*-
 2 import sys                  # 导入sys模块
 3 import pygame               # 导入pygame模块
 4 
 5 pygame.init()                               # 初始化pygame
 6 size = width, height = 640,480             # 设置窗口
 7 screen = pygame.display.set_mode(size)      # 显示窗口
 8 color = (0, 0, 0)                           # 设置颜色
 9 
10 ball = pygame.image.load("ball.png")        # 加载图片
11 ballrect = ball.get_rect()                  # 获取矩形区域
12 
13 speed = [5, 5]                              # 设置移动的X轴、Y轴距离
14 clock = pygame.time.Clock()                 # 设置时钟
15                                             # 执行死循环,确保窗口一直显示
16 while True:
17     clock.tick(60)                          # 每秒执行60次
18     # 检查事件
19     for event in pygame.event.get():
20         if event.type == pygame.QUIT:       # 如果单击关闭窗口,则退出
21             pygame.quit()                   # 退出pygame
22             sys.exit()
23 
24     ballrect = ballrect.move(speed)         # 移动小球
25     # 碰到左右边缘
26     if ballrect.left < 0 or ballrect.right > width:
27         speed[0] = -speed[0]
28     # 碰到上下边缘
29     if ballrect.top < 0 or ballrect.bottom > height:
30         speed[1] = -speed[1]
31 
32     screen.fill(color)                      # 填充颜色
33     screen.blit(ball, ballrect)             # 将图片画到窗口上
34     pygame.display.flip()                   # 更新全部显示

运行结果:

 

 

 

 

 

 

标签:ball,窗口,ballrect,Python13,pygame,speed,event
From: https://www.cnblogs.com/yisheng8/p/16945927.html

相关文章

  • Python13-实战
    实战01(模拟篮球自动弹跳)#-*-coding:utf-8-*-importsys#导入sys模块importpygame#导入pygame模块pygame.init()#初始化pygamesize=width,height=640,......