【问题标题】:Not able to move image in Pygame无法在 Pygame 中移动图像
【发布时间】:2016-09-22 03:14:56
【问题描述】:

我是 Python 的初学者。我正在尝试使用 pygame 模块移动图像。但我无法在 python 中移动图像的位置。你能帮我理解我做错了什么吗?

import pygame, sys                             
from pygame.locals import *                    
pygame.init()                                  

image = pygame.image.load("ball.jpg")
image = pygame.transform.scale(image, (100, 100))

imgrect = image.get_rect()

Canvas = pygame.display.set_mode((500, 500))
pygame.display.set_caption('Text Input')

imgrect.left = 200
imgrect.top = 200

Canvas.blit(image, imgrect)
pygame.display.update()

while True:                                    
    for event in pygame.event.get():

        if event.type == KEYDOWN :              
            if event.key == K_ESCAPE:          
                pygame.quit()                  
                sys.exit()     
            if event.key == K_UP:
                imgrect.top += 1
            if event.key == K_DOWN:
                imgrect.top -= 1

【问题讨论】:

  • 对变量使用小写名称(如canvas)而不是Canvas。第二个用于类,如果将两者混合使用,可能会使其他程序员感到困惑。

标签: python pygame


【解决方案1】:

一个基本的游戏循环应该做三件事:处理事件、更新和绘制。我看到你更新矩形位置的逻辑,但你没有在新位置重绘图像。

我在游戏循环的底部添加了线条来绘制场景。

while True: 
    # handle events
    # update logic

    # draw
    Canvas.fill((0, 0, 0))  # Clears the previous image.
    Canvas.blit(image, imgrect)  # Draws the image at the new position.
    pygame.display.update()  # Updates the screen.

【讨论】:

  • 另外,如果背景是黑色以外的其他颜色,只需更改 Canvas.fill((R, G, B)) 中的 R、G、B 值以匹配当前背景颜色。或者如果有背景图片,请将Canvas.fill((0, 0, 0)) 替换为Canvas.blit(bg_image, (0, 0))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-02
  • 1970-01-01
  • 2016-11-11
  • 2020-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多