我正在读一本名为“为绝对初学者编写更多Python编程”的书,我正在尝试编写第27页(动画矩形)的代码,当然还有改进。
我清楚地告诉pygame改变形状的x值,但它没有移动。我希望形状在屏幕上水平移动,当它到达另一端时转向,反之亦然。
这是代码:
# Animated Rectangle
#
# Demonstrating the basics of ANIMATION!!!
#
# ---------------------------------------------------
import pygame, sys
from pygame.locals import *
WHITE = 255, 255, 255
GREEN = 0, 255, 255
# rectangle properties
COLOUR = GREEN
POS_X = 400 # position
POS_Y = 200
THICKNESS = 0
VELOCITY = 1
pygame.init()
SURFACE = pygame.display.set_mode((600, 500))
SURFACE.fill(WHITE)
pygame.display.set_caption("Animationing")
if POS_X > 400 or POS_X < 100:
VELOCITY = -VELOCITY
def draw(POS_X, VELOCITY):
pygame.draw.rect(SURFACE, COLOUR, (POS_X, POS_Y, 100, 100), THICKNESS)
POS_X -= VELOCITY # HERE IS THE SOURCE OF MY PROBLEM
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
draw(POS_X, VELOCITY)
这就是问题所在;
def draw(POS_X, VELOCITY):
pygame.draw.rect(SURFACE, COLOUR, (POS_X, POS_Y, 100, 100), THICKNESS)
POS_X -= VELOCITY # HERE IS THE SOURCE OF MY PROBLEM
pygame.display.update()
编辑:有人试图修复我的语法。我喜欢这样,至少你可以理解它。
编辑2:我的问题因为偏离主题而被搁置,所以我试图修复它。
答案 0 :(得分:1)
您遇到问题,因为您对全局变量和局部变量POS_X
这创建局部变量POS_X
def draw(POS_X, VELOCITY):
并在此函数中更改本地POS_X
使用global
访问全局POS_X
(在此功能之外创建)
def draw(VELOCITY):
global POS_X
然后调用它
draw(VELOCITY)
BTW:有规则(PEP8):仅对常量值使用大写变量,如颜色WHITE,GREEN。
修改强>
您的代码可能如下所示
import pygame, sys
from pygame.locals import *
#---------------------
# constants
WHITE = (255, 255, 255)
GREEN = ( 0, 255, 255)
#---------------------
# rectangle properties
color = GREEN
pos_x = 400 # position
pos_y = 200
thickness = 0
velocity = 1
#---------------------
# classes and functions
def move_player():
global pos_x, velocity
pos_x -= velocity
if pos_x > 400 or pos_x < 100:
velocity = -velocity
def draw_player():
pygame.draw.rect(screen, color, (pos_x, pos_y, 100, 100), thickness)
#---------------------
# GAME
pygame.init()
screen = pygame.display.set_mode((600, 500))
pygame.display.set_caption("Animationing")
# mainloop
running = True
while running:
# events
for event in pygame.event.get():
if event.type == QUIT:
running = False
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
# moves
move_player()
# move_enemy()
# collision detection - nothing yet
# draws
screen.fill(WHITE)
draw_player()
# draw_enemy()
pygame.display.update()
# clock - to keep constant speed - nothing yet
# quit
pygame.quit()