如何在pygame中将图像附加到矩形?

时间:2019-02-05 00:44:23

标签: python image pygame

我需要帮助将图像附加到pygame中的矩形上。我正在尝试用python创建蛇游戏(您知道那是一个吃苹果并长出大笑的游戏),我想将我老师的脸附加到蛇。

我已经尝试定义一个变量以导入图像,然后将矩形重命名为该图像,但是似乎没有任何效果。

snakeFace = pygame.image.load("Morrison.jpg").convert_alpha()
rect = snakeFace.get_rect()
screenWidth = 500
X=50
y= 50
height = 20
vel = 20
run = True
lastKey = None
while run:
    pygame.time.delay(10) #1/2 milisecond delay
for event in pygame.event.get():
    if event.type == pygame.QUIT:
        run = False #this controls the "X" button
    if event.type == pygame.KEYDOWN:
        lastKey = event.key

    keys = pygame.key.get_pressed()
    if lastKey == pygame.K_LEFT and x > vel:
        x-=vel
    if lastKey == pygame.K_RIGHT and x< screenWidth - width -vel:
        x+=vel
    if lastKey == pygame.K_DOWN and y < screenWidth - height - vel:
        y+= vel
    if lastKey == pygame.K_UP and y > vel:
        y-=vel

    win.fill((0,0,0))
    pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
    pygame.display.update()

我希望有一个正方形,上面有我的老师的脸,在按下屏幕上的特定键之后,它会在屏幕上四处运行,但它只是规则的旧红色正方形。

2 个答案:

答案 0 :(得分:0)

这是一个红色正方形,因为代码正在绘制一个红色正方形:

pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))

改为绘制snakeFace位图:

win.blit(snakeFace, (x, y))

答案 1 :(得分:0)

这是我用来将图像添加到矩形对象的完整示例代码。

 import pygame

  vel = 5

  pygame.init()

  screen = pygame.display.set_mode((800,600))

pygame.display.set_caption('captions')
icon = pygame.image.load('test123.jpg')
pygame.display.set_icon(icon)

playerimg = pygame.image.load('test123.jpg')
playerx = 370
playery = 480


def player():
    screen.blit(playerimg,(playerx,playery))

running = True
while running:

    screen.fill((0, 0, 0))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        keys = pygame.key.get_pressed()

        if keys[pygame.K_a] and playerx > vel:
            playerx += vel

    player()
    pygame.display.update()