0

I'm just getting started with PyGame. Here, I'm trying to draw a rectangle, but it's not rendering.

Here's the whole program.

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 and self.y are currently 0 and 0. Note that this is not a finished program, all it should do is draw a red square on a green background that can be controled by the WASD keys.

4

3 回答 3

5

让我们看一下主循环的一部分:

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()
    ....

这会将整个屏幕着色为绿色,然后在绿色屏幕上绘制您的矩形。

于 2013-04-30T17:33:43.713 回答
2

这更像是一个扩展的评论和问题,而不是一个答案。

下面画一个红色方块。对你起作用吗?

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()
于 2013-04-30T02:22:46.933 回答
0

检查这些链接:

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)
于 2013-04-30T01:51:52.383 回答