简体   繁体   English

新的pygame,画了一个矩形,为什么我不能移动它?

[英]New to pygame, drew a rectangle, why can't I move it?

This is my code: 这是我的代码:

import pygame, sys
from pygame.locals import *

pygame.init()

window = pygame.display.set_mode((800, 600))
pygame.display.set_caption('window')

black = (0,0,0)
white = (255, 255, 255)

logo = pygame.image.load('logo.png').convert_alpha()

clock = pygame.time.Clock()

# Sprites
m1 = pygame.image.load('m1.png').convert_alpha()
m2 = pygame.image.load('m2.png').convert_alpha()


mci = 1

x, y = 0, 0

run = True

while run:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

        if event.type == pygame.KEYDOWN:
            if event.type == pygame.K_LEFT:
                x -= 10

            if event.type == pygame.K_RIGHT:
                x += 10

            if event.type == pygame.K_UP:
                y -= 10

            if event.type == pygame.K_DOWN:
                y += 10




        window.fill(white)

        pygame.draw.rect(window, black,(x,y, 50, 50))

        pygame.display.flip()

        clock.tick(10)

Everything shows up, but I can't move the rectangle with my arrow keys, and I always get an error after I quit out of it, help.. Thanks in advance! 一切都显示出来了,但是我不能用我的箭头键移动矩形,并且在我退出它之后总是出错,帮助..在此先感谢! PS I'm obviously copying from a tutorial, but i'm not sure what I've done wrong? PS我显然是从教程中复制,但我不确定我做错了什么?

As you worked out, you need to use event.key == ... . 当你解决问题时,你需要使用event.key == ... You probably also want to watch the nesting of your loop, currently you have: 您可能还想观看循环的嵌套,目前您有:

while running:
    for event in list_of_events:
        process_event
        draw_to_screen
        wait_a_while

This caused a problem in another question ( https://stackoverflow.com/a/13866804/2372604 ). 这在另一个问题( https://stackoverflow.com/a/13866804/2372604 )中引起了问题。 What you probably want is something more like: 您可能想要的更像是:

while running:
    for event in list_of_events:
        process_event

    draw_to_screen
    wait_a_while

You might also want to change pygame.quit(); sys.exit() 您可能还想更改pygame.quit(); sys.exit() pygame.quit(); sys.exit() to run = false and then add pygame.quit() at the end of the program. pygame.quit(); sys.exit() run = false ,然后在程序结束时添加pygame.quit()

我写的event.type而不是event.key的错误。

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

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