[英]Pygame program failing to draw as expected
我是pygame的新手,我期待顯示為青色並繪制矩形。 窗口出現了,但是不是青色的並且沒有矩形?
我相信這與順序或間距有關。 在添加矩形之前,一切正常。
import pygame
import sys
from pygame.locals import *
pygame.init()
cyan = (0,255,255)
soft_pink = (255,192,203)
screen_width = 800
screen_height = 600
gameDisplay = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('''example''')
pygame.draw.rect(gameDisplay,soft_pink,(389,200),(300,70),4)
gameDisplay.fill(cyan)
gameExit = True
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
您對Python代碼的格式應格外小心。 測試您的代碼並修復while循環的格式會發現問題:
C:\src\python\pygame1>python buggy.py
Traceback (most recent call last):
File "buggy.py", line 16, in <module>
pygame.draw.rect(gameDisplay,soft_pink,(389,200),(300,70),4)
TypeError: function takes at most 4 arguments (5 given)
如果僅用正確數量的參數替換pygame.draw.rect
調用,它將顯示一個青色窗口。 我測試了以下替換行:
pygame.draw.rect(gameDisplay,soft_pink,(389,200,300,70))
初始化pygame屏幕時,將返回一個可以填充的表面,並且應在while循環中連續填充該表面。 我建議您也為矩形使用表面對象。 只需像這樣更改代碼:
import pygame
import sys
from pygame.locals import *
pygame.init()
cyan = (0,255,255)
soft_pink = (255,192,203)
screen_width = 800
screen_height = 600
gameDisplay = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Example') # shouldn't use triple quotes
gameExit = True
surf = pygame.Surface((200, 75)) # takes tuple of width and height
rect = surf.get_rect()
rect.center = (400, 300)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
gameDisplay.fill(cyan) # continuously paint screen cyan
surf.fill(soft_pink) # continuously paint rectangle
gameDisplay.blit(surf, rect) # position rectangle at position
請記住,連續渲染是游戲開發的基本秘密,並且按照指定的順序繪制對象。 因此,在這種情況下,您實際上會看到矩形,因為它是在屏幕之后繪制的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.