簡體   English   中英

我無法使用 pygame 移動圖像

[英]I can't move an image with pygame

import pygame
import sys
pygame.init()
weight=550
height=400
screen = pygame.display.set_mode((weight,height))
image=pygame.image.load("Capture.jpg").convert()
ix= 70
iy = 80
speed =10
imageplace = screen.blit(image,(ix,iy))
pygame.display.update()
running=True
while running:
    for event in pygame.event.get():
        pygame.time.delay(10)
        if event.type == pygame.QUIT:
            running=False
        keys=pygame.key.get_pressed()
        if event.type == pygame.MOUSEBUTTONDOWN:
            pos = pygame.mouse.get_pos()
            pos_x = pos[0]
            pos_y = pos[1]
            if (keys[pygame.K_LEFT] or keys[pygame.K_a]) and ix > 0:
                ix-=speed
            if (keys[pygame.K_RIGHT] or keys[pygame.K_d]) and ix > 0:
                ix+=speed
            if (keys[pygame.K_UP] or keys[pygame.K_w]) and ix > 0:
                iy-=speed
    
            if (keys[pygame.K_DOWN] or keys[pygame.K_s]) and ix > 0:
                iy+=speed
            
            
            if imageplace.collidepoint(pos_x,pos_y):
                print("You have clicked on button")
            else:
                print("Wrong Direction")

我嘗試使用 pygame 移動圖像,但沒有成功。 我是新來的。 我在 inte.net 上找不到任何東西,我也不明白。

請參閱如何在按住鍵時使精靈移動並且您必須在每一幀中重繪場景。 典型的 PyGame 應用程序循環必須:


基於您的代碼的示例:

import pygame

pygame.init()
width, height = 550, 400
screen = pygame.display.set_mode((width, height))
clock = pygame.time.Clock()
image = pygame.image.load("Capture.jpg").convert()
imageplace = image.get_rect(topleft = (70, 80))
speed = 5

running=True
while running:
    clock.tick(100)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running=False
        if event.type == pygame.MOUSEBUTTONDOWN:
            if imageplace.collidepoint(event.pos):
                print("You have clicked on button")
            else:
                print("Wrong Direction")

    keys = pygame.key.get_pressed()        
    if (keys[pygame.K_LEFT] or keys[pygame.K_a]) and imageplace.left > 0:
        imageplace.x -= speed
    if (keys[pygame.K_RIGHT] or keys[pygame.K_d]) and imageplace.right < width:
        imageplace.x += speed
    if (keys[pygame.K_UP] or keys[pygame.K_w]) and imageplace.top > 0:
        imageplace.y -= speed
    if (keys[pygame.K_DOWN] or keys[pygame.K_s]) and imageplace.bottom < height:
        imageplace.y += speed

    screen.fill((0, 0, 0))
    screen.blit(image, imageplace)
    pygame.display.update()

pygame.quit()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM