我有一个使用pygame的python程序,但是当我运行它时,它在pygame.display.update行上给了我一个语法错误。我不确定是什么原因造成的。任何帮助表示赞赏!
import pygame, sys
import time
from pygame.locals import *
pygame.init()
area = pygame.display.set_mode((400, 300))
red=(255, 0, 0)
black=(0, 0, 0)
fps = 30
clock=pygame.time.Clock()
x=100
y=100
a=0
b=0
pygame.display.set_caption('Reddy For School')
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN and event.key == pygame.K_UP:
b=-10
if event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN:
b=10
if event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:
a=-10
if event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
a=10
if event.type == pygame.KEYUP and event.key == pygame.K_UP:
b=0
if event.type == pygame.KEYUP and event.key == pygame.K_DOWN:
b=0
if event.type == pygame.KEYUP and event.key == pygame.K_LEFT:
a=0
if event.type == pygame.KEYUP and event.key == pygame.K_RIGHT:
a=0
x+=a
y+=b
pygame.draw.rect(area, red, (x, y, 100, 100)
python.display.update()
area.fill(black)
clock.tick(fps)
答案 0 :(得分:0)
根据评论,您缺少括号。
我不确定python.display.update()
试图达到什么目的,但是我想将显示更新刷新到屏幕上。我用pygame.display.flip()
代替了。
也有几个绘画问题-代码绘制了一个红色正方形,但随后用黑色填充了屏幕。这些需要重新排序。
同样,您的主事件循环没有完全退出(在Linux下,我无法使用标题栏(x)关闭窗口)。最后,您尚未参数化窗口的宽度和高度。很快,您将需要计算一些依赖于窗口宽度的内容(例如:居中对齐),因此最好从一个参数开始,而不是在整个代码中都包含“ 400”和“ 300”。
import pygame, sys
import time
from pygame.locals import *
pygame.init()
window_width = 400
window_height = 300
area = pygame.display.set_mode((window_width, window_height))
red=(255, 0, 0)
black=(0, 0, 0)
fps = 30
clock=pygame.time.Clock()
x=100
y=100
a=0
b=0
pygame.display.set_caption('Reddy For School')
running = True
while running:
for event in pygame.event.get():
# check for closing the window
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN and event.key == pygame.K_UP:
b=-10
if event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN:
b=10
if event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:
a=-10
if event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
a=10
if event.type == pygame.KEYUP and event.key == pygame.K_UP:
b=0
if event.type == pygame.KEYUP and event.key == pygame.K_DOWN:
b=0
if event.type == pygame.KEYUP and event.key == pygame.K_LEFT:
a=0
if event.type == pygame.KEYUP and event.key == pygame.K_RIGHT:
a=0
x+=a
y+=b
area.fill(black)
pygame.draw.rect(area, red, (x, y, 100, 100) )
clock.tick(fps)
pygame.display.flip() #quicker process to draw things
pygame.quit()