使pygame绘制立方体,无论用户单击何处

时间:2018-09-06 17:18:35

标签: python pygame draw

我想做一种“关卡编辑器”作为练习。 我有以下代码:

import pygame

running = True
pygame.init()
screen = pygame.display.set_mode((800, 500))

class Cube:
    def update(self):
        self.cx, self.cy = pygame.mouse.get_pos()
        self.square = pygame.Rect(self.cx, self.cy, 50, 50)

    def draw(self): 
        pygame.draw.rect(screen, (255, 0, 0), self.square)

cube = Cube()
drawing_cube = False
drawing_cube2 = False

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            cube.update()
            drawing_cube = True

    screen.fill((0, 255, 0))
    if drawing_cube:
        cube.draw()
    pygame.display.flip()


pygame.quit()

但是,它不会创建多个正方形。它只是重新定位已经创建的正方形。

2 个答案:

答案 0 :(得分:0)

它完全按照您的要求进行操作:更新游戏中唯一的一个Cube对象,然后重新绘制屏幕和该对象。如果要多个多维数据集,则必须创建每个多维数据集。也许是这样的:

cube_list = []          # List of all cubes

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:   # Make a new cube
            cube = Cube()
            cube.update()
            cube_list.append(cube)
            drawing_cube = True

    screen.fill((0, 255, 0))
    if drawing_cube:           #New cube made; draw them all.
        for cube in cube_list:
            cube.draw()

    pygame.display.flip()

现在,作为学生的练习,您可以简化一下,使其仅将最新的多维数据集添加到现有屏幕上,而不是为每个新的多维数据集重新绘制整个游戏区域吗?

答案 1 :(得分:0)

谢谢,修剪!但是对于那些在我后面阅读本文的人,这里是完整的代码:

import pygame

cube_list = []
running = True
pygame.init()
screen = pygame.display.set_mode((800, 500))

class Cube:
    def update(self):
        self.cx, self.cy = pygame.mouse.get_pos()
        self.square = pygame.Rect(self.cx, self.cy, 50, 50)

    def draw(self): 
        pygame.draw.rect(screen, (255, 0, 0), self.square)

cube = Cube()
drawing_cube = False
drawing_cube2 = False

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:   # Make a new cube
            cube = Cube()
            cube.update()
            cube_list.append(cube)
            drawing_cube = True

    screen.fill((0, 255, 0))
    if drawing_cube:           #New cube made; draw them all.
        for cube in cube_list:
            cube.draw()

    pygame.display.flip()


pygame.quit()

干杯!

PS我已将您的答案标记为已接受