我正在使用
pip
版本的 Pygame,并且我已经编写了所有代码。代码中绝对没有错误(据我所知)。我的意思是,可能存在某种类型的隐藏错误,但我所看到的只是屏幕右上角的日常✔
。我运行它,它几乎没有显示想要的输出。就像一大块代码正在起作用......null.
无论如何,这是我的代码。
import pygame as pg
import pygame.display
pg.init()
x = 1600
y = 900
scrn = pg.display.set_mode((x, y))
red = (255, 0, 0)
white = (255, 255, 255)
grey = (128, 128, 128)
scrn.fill(white)
pg.draw.rect(scrn, grey, pg.Rect(30, 30, 60, 60))
pg.display.flip()
def message(msg, colour):
mesg = font_style.render(msg, True, colour)
pg.display.set_caption("Toronto Raptors - Stats Viewer by Krish")
new_icon = pg.image.load("Raptors-Logo.png")
pg.display.set_icon(new_icon)
players = ["Pascal Siakam", "pascal siakam", "PASCAL SIAKAM", "Pascal siakam", "pascal Siakam", "Scottie Barnes", "scottie barnes", "SCOTTIE BARNES", "Scottie barnes", "scottie Barnes", "Jakob Poeltl", "jakob poeltl" "JAKOB POELTL", "Jakob poeltl", "jakob Poeltl"]
pg.draw.rect(scrn, grey, pg.Rect(30, 30, 60, 60))
pygame.display.flip()
def main():
screen = pg.display.set_mode((900, 600))
font = pg.font.Font(None, 32)
clock = pg.time.Clock()
input_box = pg.Rect(25, 540, 140, 32)
color_inactive = pg.Color('red2')
color_active = pg.Color((30, 30, 30))
color = color_inactive
active = False
text = ''
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
if event.type == pg.MOUSEBUTTONDOWN:
if input_box.collidepoint(event.pos):
active = not active
else:
active = False
color = color_active if active else color_inactive
if event.type == pg.KEYDOWN:
if active:
if event.key == pg.K_RETURN:
print(text)
text = ''
elif event.key == pg.K_BACKSPACE:
text = text[:-1]
else:
text += event.unicode
screen.fill((white))
txt_surface = font.render(text, True, color)
width = max(200, txt_surface.get_width()+10)
input_box.w = width
screen.blit(txt_surface, (input_box.x+5, input_box.y+5))
pg.draw.rect(screen, color, input_box, 2)
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
pg.init()
main()
pg.quit()
要么是 Pygame 出了问题,要么是我的代码有问题。
未显示的部分是我的矩形,即使代码完全没问题。
pg.draw.rect(scrn, grey, pg.Rect(30, 30, 60, 60))
pg.display.flip()
最后的if语句表示如果直接运行这个脚本,则调用main()。这意味着您在 main() 之前编写的所有其他代码都不会运行,除非它作为包导入。因此,您看不到矩形。将此设置代码移至条件语句或主函数中应该可以解决您的问题。另外,在游戏循环之外更新屏幕也很奇怪。您还在该代码中绘制了该矩形两次,这是不必要的