raf*_*ufi 0 python pygame render rect draw
我刚开始使用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)
Run Code Online (Sandbox Code Playgroud)
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))
Run Code Online (Sandbox Code Playgroud)
在Hero类的draw函数中,您正在绘制矩形。在主循环中,您正在调用hero.draw(),然后在处理完输入之后,您正在调用screen.fill()。这是在您刚刚绘制的矩形上绘制的。尝试这个:
while True:
screen.fill((0, 255, 0))
hero.draw()
keysPressed = pygame.key.get_pressed()
....
Run Code Online (Sandbox Code Playgroud)
这样会将整个屏幕变成绿色,然后在绿色屏幕上绘制矩形。
| 归档时间: |
|
| 查看次数: |
4533 次 |
| 最近记录: |