简体   繁体   English

无法在 Pygame 中跨屏幕移动图像

[英]Can't move an image across screen in Pygame

I'm a beginner in Python, and I am trying to come up with a function to draw a square which moves horizontally and vertically across the screen with the help of Pygame.我是 Python 的初学者,我正在尝试想出一个 function 来绘制一个在 ZC16872077957A36F10149CB183A1 的帮助下在屏幕上水平和垂直移动的正方形。 The square should move as we click the arrows in the keyboard.当我们单击键盘上的箭头时,正方形应该会移动。

My issue: although the square is shown in screen, it doesn't move at all, yet Python isn't showing any kind of error.我的问题:虽然正方形显示在屏幕上,但它根本不动,但 Python 没有显示任何错误。

Would anyone know what's missing?有人会知道缺少什么吗? Thanks in advance!提前致谢!

Here's what I've written so far:这是我到目前为止所写的:

import pygame

altura_tela = 600
largura_tela = 800
tela = pygame.display.set_mode((largura_tela, altura_tela))

vermelho = (255, 0, 0)

altura_quadrado = 100
largura_quadrado = 100

def desenhaQuadrado(quadrado):
    pygame.draw.rect(tela, vermelho, (350,250,largura_quadrado, altura_quadrado))

def posicaoquadrado(quadradoPos):
    tela.blit(quadrado, (quadradoPos[0],quadradoPos[1]))

def moveQuadrado(teclas, quadradoPos):
    if teclas[0] and quadradoPos[1] > 0:
        quadradoPos[1] -= 20
    elif teclas[2] and quadradoPos[1] < 420:
        quadradoPos[1] += 20
    if teclas[1] and quadradoPos[0] > 0:
        quadradoPos[0] -= 20
    elif teclas[3]and quadradoPos[0] < 570:
        quadradoPos[0] += 20
    return quadradoPos

def main():
    pygame.init()
    teclas = [False, False, False, False]
    quadradoPos = [350,250]

    pygame.display.set_caption('Movimentação do Quadrado')

    terminou = False
    while not terminou:

        for event in pygame.event.get():

            if event.type == pygame.QUIT:
                terminou = True

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    teclas[0] = True
                elif event.key == pygame.K_DOWN:
                    teclas[1] = True
                elif event.key == pygame.K_LEFT:
                    teclas[2] = True
                elif event.key == pygame.K_RIGHT:
                    teclas[3] = True

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_UP:
                    teclas[0] = False
                elif event.key == pygame.K_DOWN:
                    teclas[1] = False
                elif event.key == pygame.K_LEFT:
                    teclas[2] = False
                elif event.key == pygame.K_RIGHT:
                    teclas[3] = False

            quadradoPos = moveQuadrado(teclas, quadradoPos)
            desenhaQuadrado(quadradoPos)

            pygame.display.update()


    pygame.display.quit()

    pygame.quit()

if __name__ == '__main__':
    main()

In your function:在您的 function 中:

def desenhaQuadrado(quadrado):
    pygame.draw.rect(tela, vermelho, (350,250,largura_quadrado, altura_quadrado))

You are passing an argument quadrado but you never use it.您正在传递一个参数quadrado但您从不使用它。 Also your coordinates never update 350, 250 .此外,您的坐标永远不会更新350, 250 So this function basically draws same rect over and over again.所以这个 function 基本上一遍又一遍地绘制相同的矩形。

I modified your code:我修改了你的代码:

import pygame

clock = pygame.time.Clock()

altura_tela = 600
largura_tela = 800
tela = pygame.display.set_mode((largura_tela, altura_tela))

FPS = 30

vermelho = (255, 0, 0)

altura_quadrado = 100
largura_quadrado = 100


def redraw(quadradoPos):
    tela.fill(pygame.Color("white"))
    pygame.draw.rect(tela, vermelho, (quadradoPos[0], quadradoPos[1], largura_quadrado, altura_quadrado))
    pygame.display.update()


def main():
    pygame.init()
    quadradoPos = [300,250]
    pygame.display.set_caption('Movimentação do Quadrado')

    terminou = False
    while not terminou:

        clock.tick(FPS)

        for event in pygame.event.get():

            if event.type == pygame.QUIT:
                terminou = True

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP and quadradoPos[1] > 0:
                    quadradoPos[1] -= 50
                elif event.key == pygame.K_DOWN and quadradoPos[1] <= altura_tela - altura_quadrado:
                    quadradoPos[1] += 50
                elif event.key == pygame.K_LEFT and quadradoPos[0] >= 0:
                    quadradoPos[0] -= 50
                elif event.key == pygame.K_RIGHT and quadradoPos[0] <= largura_tela - largura_quadrado:
                    quadradoPos[0] += 50

            redraw(quadradoPos)

    pygame.quit()

if __name__ == '__main__':
    main()

NOTE:笔记:

-do not forget tela.fill(pygame.Color("white")) , otherwise you will get "traces" of all rects that are drawn on the screen. - 不要忘记tela.fill(pygame.Color("white")) ,否则您将获得在屏幕上绘制的所有矩形的“痕迹”。

-I added clock in order to control the frame rate. -我添加了clock以控制帧速率。

-You cannot blit rect on the screen like you did in posicaoquadrado(quadradoPos) it will cause the TypeError . - 你不能像在posicaoquadrado(quadradoPos)中那样在屏幕上对rect进行 blit ,它会导致TypeError You can blit Surface only.您只能对Surface进行 blit。

Hope this answers your question.希望这能回答你的问题。

There are some static values inside the desenhaQuadrado function desenhaQuadrado function 中有一些 static 值

def desenhaQuadrado(quadrado):
    pygame.draw.rect(tela, vermelho, (350,250,largura_quadrado, altura_quadrado))

Change it to the code bellow and it will move.将其更改为下面的代码,它会移动。

def desenhaQuadrado(quadrado):
    pygame.draw.rect(tela, vermelho, (quadrado[0],quadrado[1],largura_quadrado, altura_quadrado))

Although you will have some others problems to solve as you will see.尽管您将看到其他一些问题需要解决。 I created a script that is basicly what you want, check it in case you want some help https://github.com/eng-robsonsampaio/pygame_move_square.git我创建了一个基本上是你想要的脚本,如果你需要一些帮助,请检查

import pygame
from pygame.locals import *

UP = 0
DOWN = 1
LEFT = 2
RIGHT = 3
GAME_ON = True
SPEED = 20

screen = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()

square = pygame.Surface((50,50))
square.fill((255,0,0))
POS = [(200,200)]

def move_square(direction):
    if UP == direction:
        POS.append((POS[0][0], POS[0][1] - 20))
    elif direction == DOWN:
        POS.append((POS[0][0], POS[0][1] + 20))
    elif direction == LEFT:
        POS.append((POS[0][0] - 20, POS[0][1]))
    else:
        POS.append((POS[0][0] + 20, POS[0][1]))
    POS.pop(0)


while GAME_ON:

    for event in pygame.event.get():
        if event.type == QUIT:
            GAME_ON = False
        if event.type == KEYDOWN:
            if event.key==K_UP:
                print("UP")
                move_square(UP)                
            elif event.key==K_LEFT:
                print("LEFT")
                move_square(LEFT)               
            elif event.key==K_DOWN:
                print("DOWN")
                move_square(DOWN)                
            elif event.key==K_RIGHT:
                print("RIGHT")
                move_square(RIGHT)

    screen.fill((0,0,0))
    screen.blit(square, POS[0])
    pygame.display.update()

pygame.quit()

I also have a snake game tutorial in medium: https://medium.com/@robsonsampaio90/snake-game-in-python-with-pygame-291f5206a35e我还有一个中等的蛇游戏教程: https://medium.com/@robsonsampaio90/snake-game-in-python-with-pygame-291f5206a35e

You might find some help in this links.您可能会在此链接中找到一些帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM