Python 在 Pygame 中移动矩形

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32061507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:56:40  来源:igfitidea点击:

Moving A Rectangle in Pygame

pythonpygame

提问by AKcoArts

I'm trying to make a game and encountered a problem... I cant move the rectangle, and it doesn't give me an error code either?.. I think the problem is that it keeps making the rectangle over and over again in the while loop... but I don't know how to fix this..

我正在尝试制作游戏并遇到问题......我无法移动矩形,它也没有给我错误代码?..我认为问题在于它一遍又一遍地制作矩形在while循环中......但我不知道如何解决这个......

#! /usr/bin/env python

import os
import random
import pygame
import math
import sys

os.environ["SDL_VIDEO_CENTERED"] = "1"

screen = pygame.display.set_mode((600, 600))
pygame.display.set_caption("LEVEL 2 = Find the Correct Square!")

clock = pygame.time.Clock()

class Player(object):
    def __init__(self):
        self.rect = pygame.draw.rect(screen, (0, 0, 128), (64, 54, 16, 16))

    def handle_keys(self):
        key = pygame.key.get_pressed()
        dist = 1
        if key[pygame.K_LEFT]:
           self.rect.move(-1, 0)
        if key[pygame.K_RIGHT]:
           self.rect.move(1, 0)
        if key[pygame.K_UP]:
           self.rect.move(0, -1)
        if key[pygame.K_DOWN]:
           self.rect.move(0, 1)

    def draw(self, surface):
        pygame.draw.rect(screen, (0, 0, 128), (64, 54, 16, 16))

pygame.init()

player = Player()
clock = pygame.time.Clock()

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

        screen.fill((255, 255, 255))

        player.draw(screen)
        player.handle_keys()
        pygame.display.update()

        clock.tick(40)

采纳答案by John La Rooy

You need to make a few changes to your Playerclass. You either need to reassign self.rectto the result of self.rect.move()or use the inplace variant self.rect.move_ip()

您需要对类进行一些更改Player。您需要重新分配self.rect给结果self.rect.move()或使用就地变体self.rect.move_ip()

class Player(object):
    def __init__(self):
        self.rect = pygame.rect.Rect((64, 54, 16, 16))

    def handle_keys(self):
        key = pygame.key.get_pressed()
        dist = 1
        if key[pygame.K_LEFT]:
           self.rect.move_ip(-1, 0)
        if key[pygame.K_RIGHT]:
           self.rect.move_ip(1, 0)
        if key[pygame.K_UP]:
           self.rect.move_ip(0, -1)
        if key[pygame.K_DOWN]:
           self.rect.move_ip(0, 1)

    def draw(self, surface):
        pygame.draw.rect(screen, (0, 0, 128), self.rect)

The rectangle will move once for each keypress. If you want to keep moving when you hold a key down, you need to dedent part of your main loop

每次按键都会移动一次矩形。如果您想在按住某个键时继续移动,则需要减少主循环的一部分

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

    screen.fill((255, 255, 255))

    player.draw(screen)
    player.handle_keys()
    pygame.display.update()

    clock.tick(40)

回答by Malik Brahimi

movesimply returns a new rectangle without altering the variable, so use move_ipto move in place.

move简单地返回一个新的矩形而不改变变量,所以使用move_ip原地移动。

pygame.draw.rect(surface, (0, 0, 128), self.rect) # draw the rect at a variable location

回答by user7154701

import os
import random
import pygame
import math
import sys

os.environ["SDL_VIDEO_CENTERED"] = "1"

screen = pygame.display.set_mode((600, 600))
pygame.display.set_caption("LEVEL 2 = Find the Correct Square!")

clock = pygame.time.Clock()

class Player(object):
    def __init__(self):
        self.rect = pygame.draw.rect(screen, (0, 0, 128), (64, 54, 16, 16))

    def handle_keys(self):
        key = pygame.key.get_pressed()
        dist = 1
        if key[pygame.K_LEFT]:
           self.rect.move(-1, 0)
        if key[pygame.K_RIGHT]:
           self.rect.move(1, 0)
        if key[pygame.K_UP]:
           self.rect.move(0, -1)
        if key[pygame.K_DOWN]:
           self.rect.move(0, 1)

    def draw(self, surface):
        pygame.draw.rect(screen, (0, 0, 128), (64, 54, 16, 16))

pygame.init()

player = Player()
clock = pygame.time.Clock()

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

        screen.fill((255, 255, 255))

        player.draw(screen)
        player.handle_keys()
        pygame.display.update()

        clock.tick(40)import os

回答by Apostolos

I have modified your code so that 1) it works (essential! :) and 2) one can exit from the script with [Esc] and QUIT, and not get stuck in it (also essential!) I also gave life to your 'dist' variable (which was not used) to set displacements of 10 pixels. Yet, there are still important things to be added, e.g. checking for and preventing the small rectangle getting out of the window, etc.

我已经修改了您的代码,以便 1) 它可以工作(必不可少!:) 和 2)您可以使用 [Esc] 和 QUIT 退出脚本,而不会陷入其中(也是必不可少的!)我也赋予了您的生命dist' 变量(未使用)设置 10 个像素的位移。然而,仍然有一些重要的事情需要添加,例如检查和防止小矩形离开窗口等。

import os
import random
import pygame
from pygame.locals import * # Constants
import math
import sys

os.environ["SDL_VIDEO_CENTERED"] = "1"

screen = pygame.display.set_mode((600, 600))
pygame.display.set_caption("LEVEL 2 = Find the Correct Square!")

clock = pygame.time.Clock()

class Player(object):
    def __init__(self):
        self.rect = pygame.draw.rect(screen, (0, 0, 128), (64, 54, 16, 16))
        self.dist = 10

    def handle_keys(self):
        for e in pygame.event.get():
            if e.type == QUIT:
                pygame.quit(); exit()
            elif e.type == KEYDOWN:
                key = e.key
                if key == K_LEFT:
                    self.draw_rect(-1, 0)
                elif key == K_RIGHT:
                    self.draw_rect(1, 0)
                elif key == K_UP:
                    self.draw_rect(0, -1)
                elif key == K_DOWN:
                    self.draw_rect(0, 1)
                elif key == K_ESCAPE:
                    pygame.quit(); exit()

    def draw_rect(self,x,y):
        screen.fill((255, 255, 255))
        self.rect = self.rect.move(x*self.dist, y*self.dist); pygame.draw.rect(screen, (0, 0, 128), self.rect)
        pygame.display.update()

    def draw(self, surface):
        pygame.draw.rect(screen, (0, 0, 128), (64, 54, 16, 16))

pygame.init()

player = Player()
#clock = pygame.time.Clock()
screen.fill((255, 255, 255))
player.draw(screen)
pygame.display.update()

while True:
  player.handle_keys()