我刚刚开始使用 PyGame。在这里,我试图绘制一个矩形,但它没有渲染。
这是整个程序。
import pygame
from pygame.locals import *
import sys
import random
pygame.init()
pygame.display.set_caption("Rafi's Game")
clock = pygame.time.Clock()
screen = pygame.display.set_mode((700, 500))
class Entity():
def __init__(self, x, y):
self.x = x
self.y = y
class Hero(Entity):
def __init__(self):
Entity.__init__
self.x = 0
self.y = 0
def draw(self):
pygame.draw.rect(screen, (255, 0, 0), ((self.x, self.y), (50, 50)), 1)
hero = Hero()
#--------------Main Loop-----------------
while True:
hero.draw()
keysPressed = pygame.key.get_pressed()
if keysPressed[K_a]:
hero.x = hero.x - 3
if keysPressed[K_d]:
hero.x = hero.x + 3
if keysPressed[K_w]:
hero.y = hero.y - 3
if keysPressed[K_s]:
hero.y = hero.y + 3
screen.fill((0, 255, 0))
#Event Procesing
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
#Event Processing End
pygame.display.flip()
clock.tick(20)
self.x
和 self.y
当前为 0 和 0。
请注意,这不是一个完成的程序,它要做的只是在绿色背景上绘制一个红色方块,可以通过 WASD 键控制。
让我们看看主循环的一部分:
while True:
hero.draw()
keysPressed = pygame.key.get_pressed()
if keysPressed[K_a]:
hero.x = hero.x - 3
if keysPressed[K_d]:
hero.x = hero.x + 3
if keysPressed[K_w]:
hero.y = hero.y - 3
if keysPressed[K_s]:
hero.y = hero.y + 3
screen.fill((0, 255, 0))
在 Hero 类的绘制函数中,您正在绘制矩形。 在主循环中,您调用
hero.draw()
,然后在处理输入后,您调用 screen.fill()
。 这是在您刚刚绘制的矩形上绘制的。 试试这个:
while True:
screen.fill((0, 255, 0))
hero.draw()
keysPressed = pygame.key.get_pressed()
....
这会将整个屏幕着色为绿色,然后在绿色屏幕上绘制矩形。
这更多的是扩展评论和问题,而不是答案。
下图画了一个红色的方块。 对你有用吗?
import sys
import pygame
pygame.init()
size = 320, 240
black = 0, 0, 0
red = 255, 0, 0
screen = pygame.display.set_mode(size)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screen.fill(black)
# Either of the following works. Without the fourth argument,
# the rectangle is filled.
pygame.draw.rect(screen, red, (10,10,50,50))
#pygame.draw.rect(screen, red, (10,10,50,50), 1)
pygame.display.flip()
检查这些链接:
http://www.pygame.org/docs/ref/draw.html#pygame.draw.rect
这里有一些例子:
http://nullege.com/codes/search?cq=pygame.draw.rect
pygame.draw.rect(screen, color, (x,y,width,height), thickness)
pygame.draw.rect(screen, (255, 0, 0), (self.x, self.y, 50, 50), 1)
我妈妈看到了你的主循环,我发现了错误:
while True:
screen.fill((0,255,0)) # here was hero.draw() but i replaced 'cuz it plays first that screen.fill function
keysPressed = pygame.key.get_pressed()
if keysPressed[K_a]:
hero.x -= 3 # here corrected
if keysPressed[K_d]:
hero.x += 3 # here corrected
if keysPressed[K_w]:
hero.y -= 3 # here corrected
if keysPressed[K_s]:
hero.y += 3 # here corrected
hero.draw # here was screen.fill() but i replaced cuz it not plays first than draw function