在康威的生命模拟游戏中标记正方形会将颜色更改为fas

2024-04-19 11:00:55 发布

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

我在做一个康威的生活模拟游戏,我在用颜色标记正方形时遇到了一些麻烦。我用一个矩阵来表示正方形,当我点击一个正方形时,我把值从0改为1。或者就是这样。 我第一次尝试下面的代码,但问题是,当我单击一次时,它会迅速地从有标记变为无标记变为有标记,以此类推。你知道吗

if pygame.mouse.get_pressed()[0]:
    if grid[y][x] == 0:
        mouse_x,mouse_y = pygame.mouse.get_pos()
        x = mouse_x // (size + 1)
        y = mouse_y // (size + 1)
        grid[y][x] = 1

    elif grid[y][x] == 1:
        mouse_x,mouse_y = pygame.mouse.get_pos()
        x = mouse_x // (size + 1)
        y = mouse_y // (size + 1)
        grid[y][x] = 0

比我试过的其他代码:

for event in pygame.event.get():
    if event.type == pygame.MOUSEBUTTONUP:
        if grid[y][x] == 0:
            mouse_x,mouse_y = pygame.mouse.get_pos()
            x = mouse_x // (size + 1)
            y = mouse_y // (size + 1)
            grid[y][x] = 1

        elif grid[y][x] == 1:
            mouse_x,mouse_y = pygame.mouse.get_pos()                        
            x = mouse_x // (size + 1)
            y = mouse_y // (size + 1)
            grid[y][x] = 0

但这里的问题是,方块不再被标记。你知道吗


Tags: 代码标记poseventsizegetif颜色
2条回答

你可以尝试在每次点击时添加一种冷却时间。时间(). 你知道吗

# Start of program
import time
cooldown = 0

cooleddown = time.time() - cooldown > 0.7
if pygame.mouse.get_pressed()[0] and cooleddown:
     cooleddown = time.time()
     if grid[y][x] == 0:
        mouse_x,mouse_y = pygame.mouse.get_pos()
        x = mouse_x // (size + 1)
        y = mouse_y // (size + 1)
        grid[y][x] = 1

    elif grid[y][x] == 1:
        mouse_x,mouse_y = pygame.mouse.get_pos()
        x = mouse_x // (size + 1)
        y = mouse_y // (size + 1)
        grid[y][x] = 0

time.time()所做的是返回自1970年1月1日午夜以来的当前秒数。因此,如果您在再次检查之前测试它是否已经过了一定的时间,这可能有助于解决问题。你知道吗

*这没有经过测试,您可能需要等待0.7秒,我不知道等待时间有多短

尝试在使用x和y之前设置它们,同时使用布尔值(未测试):

for event in pygame.event.get():
    if event.type == pygame.MOUSEBUTTONUP:
        mouse_x,mouse_y = pygame.mouse.get_pos()
        x = mouse_x // (size + 1)
        y = mouse_y // (size + 1)
        grid[y][x] = not grid[y][x]

相关问题 更多 >