使用pygame移动球体
大家好,我正在用pygame开发一个弹跳球的游戏。我下载了一张图片 ball.jpg
,用作球的图像,还有一张 bg.jpg
,作为背景。我尝试移动这个球,但没有成功。我的代码是:
import pygame, sys
from pygame.locals import *
pygame.init()
clocks = pygame.time.Clock()
surfaceObject = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Bounce')
mousey,mousex = 0,0
imgx = 10
imgy = 10
pixmove = 5
movement = 'down'
background = pygame.image.load('bg.jpg').convert()
ball = pygame.image.load('ball.jpg').convert_alpha()
sound = pygame.mixer.Sound('yeah.mp3')
while True:
if movement == 'down':
imgx += pixmove
if imgy < 200:
movement = 'right'
elif movement == 'right':
imgx += pixmove
if imgx < 200:
movement = 'up'
elif movement == 'up':
imgy -= pixmove
if imgy < 30:
movement = 'left'
elif movement == 'left':
imgx -= pixmove
if imgx < 30:
movement = 'down'
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
surfaceObject.blit(background,(mousex,mousey))
surfaceObject.blit(ball,(imgx,imgy))
sound.Play()
pygame.display.update()
clocks.tick(50)
当我运行这段代码时,图像没有在pygame窗口中显示出来。我把 bounce.py
文件和我下载的两张图片放在同一个文件夹里。
我想在pygame窗口中移动这个球,并显示球的图像和背景图像。希望大家能帮帮我。提前谢谢你们!
1 个回答
0
修复了代码中的缩进问题:
import time
import pygame, sys
from pygame.locals import *
pygame.init()
clocks = pygame.time.Clock()
surfaceObject = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Bounce')
mousey,mousex = 0,0
imgx = 10
imgy = 10
pixmove = 5
movement = 'down'
background = pygame.image.load('bg.jpg').convert()
ball = pygame.image.load('ball.jpg').convert_alpha()
pygame.mixer.music.load('yeah.mp3')
while True:
time.sleep(1)
if movement == 'down':
imgx += pixmove
if imgy < 200:
movement = 'right'
elif movement == 'right':
imgx += pixmove
if imgx < 200:
movement = 'up'
elif movement == 'up':
imgy -= pixmove
if imgy < 30:
movement = 'left'
elif movement == 'left':
imgx -= pixmove
if imgx < 30:
movement = 'down'
print movement
print imgx
print imgy
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
surfaceObject.blit(background,(mousex,mousey))
surfaceObject.blit(ball,(imgx,imgy))
pygame.mixer.music.play()
pygame.display.update()
clocks.tick(50)