在pygame中创建随机障碍场

问题描述 投票:0回答:1

我正在尝试在 pygame 中使用各种俄罗斯方块形状创建一个随机障碍场。我想使用这些俄罗斯方块形状随机填充 128x128 网格。我能够生成它们并使用 pygame.draw.polygon 填充网格,但其中很少有彼此重叠。如何避免不同多边形对象之间的重叠?

import pygame

pygame.init()
import random

#Create discplay screen
screen = pygame.display.set_mode((768 ,768))
total_cells = 128*128
#colors
blue = (0,0,255); red = (255,0,0); white = (255,255,255); black = (0, 0, 0); green = (0, 240, 100)

def getShape(start, width = 50):
    a = random.randint(1,8)
    RT = [start, (start[0] + 2*width, start[1]), (start[0] + 2*width, start[1] + width), (start[0] + width, start[1] + width), (start[0] + width, start[1] + 3*width), (start[0], start[1] + 3*width)]

    LT = [start, (start[0] - 2*width, start[1]), (start[0] - 2*width, start[1] + width), (start[0] - width, start[1] + width), (start[0] - width, start[1] + 3*width), (start[0], start[1] + 3*width)]

    RB = [start, (start[0] + width, start[1]), (start[0] + width, start[1] + 2*width), (start[0] + 2*width, start[1] + 2*width), (start[0] + 2*width, start[1] + 3*width), (start[0], start[1] + 3*width)]

    LB = [start, (start[0] - width, start[1]), (start[0] - width, start[1] + 2*width), (start[0] - 2*width, start[1] + 2*width), (start[0] - 2*width, start[1] + 3*width), (start[0], start[1] + 3*width)]

    if(a == 1):
        return LT
    elif(a == 2):
    return RT
    elif(a == 3):
    return LB
    elif(a == 4):
    return RB

def drawGrid():
    screen.fill(white)
    for i in range(0, 768, 6):
        pygame.draw.line(screen, black, (0, i), (768, i))
        pygame.draw.line(screen, black, (i, 0), (i, 768))

def generateObstacles(perc):
    fill_cells = round(total_cells*perc/100)
    fill_count = 0
    for i in range(0, fill_cells, 4):
        x1 = random.randint(2,126); y1 = random.randint(3,124)
    start = (6*x1, 6*y1)
    ob = getShape(start, 6)
    pygame.draw.polygon(screen, black, ob)
    fill_count += 4
    print('number of cells filled',fill_count)

def main():
    screen = pygame.display.set_mode((768 ,768))

    drawGrid()
    x1 = random.randint(2,126); y1 = random.randint(3,125)

    start = (6*x1, 6*y1)
    sp1 = getShape(start, 6)

    x1 = random.randint(1,24); y1 = random.randint(1,24)

    start = (6*x1, 6*y1)
    sp2 = getShape(start, 6)

    generateObstacles(50)

    pygame.display.flip()
    while pygame.event.wait().type != pygame.QUIT:
        pass
if __name__ == "__main__": 
    main()`

enter image description here

python datagrid
1个回答
0
投票

在四格骨牌的方块之间进行碰撞,如果它与不同四格骨牌的另一个方块碰撞,那么你可以让它去不同的地方。此过程不应与玩家发生碰撞。最好的方法是与方块碰撞。有两种方法:内置的pygame,或者大于和小于策略。或者你可以使用 pygame 多边形碰撞代替所有方块。

我希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.