我有一個非常簡單的程序。我想要的是物品類中的物品可以自行移動。pygame物體不會移動
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 = things(100,100,4)'移到while循環之前。 – Moberg
工作。非常感謝。 :D – KungFuHustled
@Moberg發表您的評論作爲回答,以便它可以被接受 –