• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

pygame - 图片移动

武飞扬头像
coding_yzh
帮助1

目录

代码段

效果展示 


代码段

  1.  
    import sys
  2.  
    import pygame
  3.  
    pygame.init()
  4.  
    # 使用pygame之前必须初始化
  5.  
     
  6.  
    LENGTH = 1000 # 主屏窗口长度
  7.  
    WIDTH = 680 # 主屏窗口宽度
  8.  
    screen = pygame.display.set_mode((LENGTH,WIDTH)) # 设置主屏窗口
  9.  
    # 说明:set_mode()可以短时间显示主屏窗口
  10.  
    pygame.display.set_caption("图片移动测试") # 设置窗口标题
  11.  
    # 说明:若不设置窗口标题,则窗口标题默认为“pygame window”
  12.  
     
  13.  
    img = pygame.image.load("t02_img.png") # 加载本地图片
  14.  
    rect = img.get_rect() # 获取图片区域
  15.  
    rect.x = 500 # 设置显示位置
  16.  
    rect.y = 340 # 设置显示位置
  17.  
     
  18.  
    def move(rect,direction): # 图片移动函数
  19.  
    # 说明:图片移动实质是改变rect.top或rect.left,并确保图片不会移出主屏窗口
  20.  
    speed = 20 # 移动速度
  21.  
    if rect.top-speed>=0 and direction == 'U': # 上
  22.  
    rect.top -= speed
  23.  
    elif rect.top rect.height speed<=WIDTH and direction == 'D': # 下
  24.  
    rect.top = speed
  25.  
    elif rect.left-speed>=0 and direction == 'L': # 左
  26.  
    rect.left -= speed
  27.  
    elif rect.left rect.width speed<=LENGTH and direction == 'R': # 右
  28.  
    rect.left = speed
  29.  
     
  30.  
    while True:
  31.  
    # 说明:while True循环可以使得主屏窗口得以保留
  32.  
     
  33.  
    screen.fill((0, 0, 0)) # 填充
  34.  
    # 说明:在更新之前填充可以覆盖之前的图片,防止图片移动后出现重影
  35.  
    screen.blit(img, rect) # 传送
  36.  
    # 说明:给主屏窗口传送移动后的图片区域
  37.  
    pygame.display.update() # 更新
  38.  
    # 说明:更新屏幕显示,给用户一种图片发生移动的视觉效果
  39.  
     
  40.  
    for event in pygame.event.get(): # 循环获取事件并监听事件状态
  41.  
    if event.type == pygame.KEYDOWN: # 按下了按键
  42.  
    if event.key == pygame.K_UP: # 上
  43.  
    move(rect,'U')
  44.  
    elif event.key == pygame.K_DOWN: # 下
  45.  
    move(rect,'D')
  46.  
    elif event.key == pygame.K_LEFT: # 左
  47.  
    move(rect,'L')
  48.  
    elif event.key == pygame.K_RIGHT: # 右
  49.  
    move(rect,'R')
  50.  
    if event.type == pygame.QUIT: # 点击了关闭按钮
  51.  
    pygame.quit() # 卸载模块
  52.  
    sys.exit() # 退出程序

学新通

效果展示 

备注:图片为170*174像素

pygame图片移动测试 20230107

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhggefja
系列文章
更多 icon
同类精品
更多 icon
继续加载