无法在python pygam中绘制rect

2024-09-28 05:16:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚开始玩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和{}当前为0和0。 请注意,这不是一个完成的程序,它所要做的只是在绿色背景上画一个红色的正方形,它可以由WASD键控制。在


Tags: importselfeventifinitdefdisplaysys
3条回答

这更多的是一个延伸的评论和问题,而不是一个答案。在

下面画一个红色正方形。对你有用吗?在

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:


    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类的draw函数中,您正在绘制rect。在主循环中,您将调用hero.draw(),然后在处理完输入之后,您将调用screen.fill()。这是在你刚刚画的矩形图上画的。试试这个:

^{pr2}$

这将使整个屏幕变绿,然后在绿色屏幕上绘制矩形。在

相关问题 更多 >

    热门问题