我有一个非常简单的程序。我想要的是事物类中的项目能够自行移动。
import pygame
import time
import random
import threading
#initilasies it
pygame.init()
#variables for height and width
global display_width
display_width= 800
global display_height
display_height= 600
#declares colours uses RGB as reference
white= (255,255,255)
black = (0,0,0)
#sets the dispaly (must be inside a tuple ())
gameDisplay = pygame.display.set_mode((display_width,display_height))
#changes the name of the window
pygame.display.set_caption("Robot Quest")
#times stuff (is gonna be used for FPS)
clock = pygame.time.Clock()
#loads up an image (not shown) must be in same directory
tankImg = pygame.image.load("tank.png")
blockImg = pygame.image.load("block.png")
class things:
def __init__(self,width,height,speed):
self.width = width
self.height = height
#if display.width doesn't work just pass the screen dimensions
self.X = display_width - self.width
self.Y= display_height - self.height
self.speed = speed
def move(self):
self.X -= self.speed
pos = self.X
return pos
def drawImage(self,imageName,x,y):
gameDisplay.blit(imageName,(x,y))
def game_loop():
#game exit value is set
game_exit = False
#when true you exit the loop, logic goes here
while not game_exit:
for event in pygame.event.get():
#method below on what to do if they press x in the corner
if event.type == pygame.QUIT:
#exit the loop
pygame.quit()
quit()
#fills the background
gameDisplay.fill(white)
block = things(100,100,4)
block.drawImage(blockImg,block.X,block.Y)
block.move()
pygame.display.update()
clock.tick(30)
game_loop()
pygame.quit()
quit()
在程序中,block.move() 执行一次,但仅此而已,因此对象保留在同一个位置,仅移动了一次位置。我尝试将 block.move() 函数放入 for 和 while 循环中,但如果这样做,程序将不会运行。谁能告诉我如何修复我的代码,以便对象连续移动,以便它从屏幕的一端移动到屏幕的另一端?
最佳答案
您似乎在每个循环中初始化了您的 block 。尝试将 block = things(100,100,4)
移动到 while 循环之前。
关于python - pygame 对象不会移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32213244/