如何使用pygame创建多个相等距离的形状?

时间:2017-05-19 04:14:23

标签: python-2.7 pygame

在#Trees下,我写了一个for循环。第一个循环工作正常,x = 0。

然而,第二个循环虽然x = 300,但形状并没有从原来的位置移开。

这应该做的是在第二个" for循环"之后改变我的形状的x坐标。完成了在树上创建叶子。

import pygame
from pygame.locals import *

pygame.init()

window = pygame.display.set_mode([640,600])

# color reference
white = (255,245,238)
blue = (65,105,225)
green = (154,205,50)
grey = (105,105,105)
lightblue = (176,196,222)
brown = (93, 64, 55)
darkgreen = (0, 121, 107)

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()

    # Sky
    window.fill((135,206,250))
    # Pond
    pygame.draw.rect (window, (blue), Rect((0,510),(640,100)))
    # House base
    pygame.draw.rect (window, (white), Rect((100,310),(200,190)))
    # Grass
    pygame.draw.rect (window, (green), Rect((0,500),(440,100)))
    # Windowsill
    pygame.draw.rect (window, (grey), Rect((200,420),(80,10)))
    # Window/Door
    pygame.draw.rect (window, (lightblue), Rect((206,360),(70,60)))
    pygame.draw.rect (window, (lightblue), Rect((115,410),(70,90)))
    # Doorknob
    pygame.draw.circle(window, (grey), (125, 459), 5, 0)
    # Roof
    pygame.draw.polygon (window, (grey), ((100,310),(203,260),(299,310)))
    # Trees
    for trees in range(3):
        y = 0
        x = 0
        pygame.draw.rect (window, (brown), Rect((40 + x,470),(20,30)))
        for leaves in range(3):
            pygame.draw.polygon (window, (darkgreen), ((10 + x,470 - y),(50 + x,410 - y),(90 + x,470 - y)))
            y = y + 40
            if leaves == 2:
                x = x + 300


    pygame.display.flip()

我的目标是在房子的两边都有一棵树,使用for循环。 一点帮助将非常感激。

2 个答案:

答案 0 :(得分:1)

这似乎有效

# Trees
y = 0
x = 0
for trees in range(2):
    pygame.draw.rect (window, (brown), Rect((40 + x,470),(20,30)))
    for leaves in range(3):
        pygame.draw.polygon (window, (darkgreen), ((10 + x,470 - y),(50 + x,410 - y),(90 + x,470 - y)))
        y = y + 40
        if leaves == 2:
            x = x + 300
            y = y - 120

for循环不断将x和y值更改回零,因此我将叶子的范围设置回3并将x和y累加器变量移动到循环上方。

答案 1 :(得分:1)

您实际上并不需要for循环上方的yx变量,因为您可以通过可选的"步骤" range的论点。例如,list(range(0, 81, 40))为您提供[0, 40, 80]

for x in range(0, 301, 300):
    pygame.draw.rect (window, (brown), Rect((40 + x,470),(20,30)))
    for y in range(0, 81, 40):
        pygame.draw.polygon(
            window, darkgreen,
            ((10+x, 470-y), (50+x, 410-y), (90+x, 470-y)))