繁体   English   中英

PyGame Conway的《生活游戏》,重新绘制精灵

[英]PyGame Conway's Game of Life, redraw sprites

当我更新程序应在每个位置使用的图像阵列时,我可以将活细胞放置在死细胞上,但是原始细胞不会消失,也不能在活细胞上添加死细胞。 有人修复吗?

原始文件

import pygame, pygamehandle, standard, sys
from pygame.locals import *
loader = pygamehandle.load()

pygame.mixer.music.load('music1.ogg')
pygame.mixer.music.play(-1, 0.0)

SCREEN_SIZE = (600, 400)
fps = 24
fpsClock = pygame.time.Clock()
imgs = ["live.png", "dead.png", "background.png"]
icon = "icon.png"

screen = loader.loadScreen(SCREEN_SIZE, "Game of Life", icon)

lImgs = loader.listImgLoad(imgs)

objects, grid = loader.grid(SCREEN_SIZE, lImgs[1])

loader.blit(objects, grid)

pygame.display.update()

while True:
    mouseClicked = False
    fpsClock.tick(fps)

    for i in pygame.event.get():
        if i.type == MOUSEBUTTONDOWN:
            if i.button == 1:
                mouseposx, mouseposy = pygame.mouse.get_pos()
                mouseposx = (mouseposx // 20) * 20
                mouseposy = (mouseposy // 20) * 20
                mousepos = (mouseposx, mouseposy)
                index = grid.index(mousepos)
                objects[index] = lImgs[0]

            if i.button == 2:
                mouseposx, mouseposy = pygame.mouse.get_pos()
                mouseposx = (mouseposx // 20) * 20
                mouseposy = (mouseposy // 20) * 20
                mousepos = (mouseposx, mouseposy)
                index = grid.index(mousepos)
                objects[index] = lImgs[1]


        if i.type == QUIT:
            pygame.quit()
            sys.exit()

    pygame.Surface.fill(screen, [0, 0, 0])
    loader.blit(objects, grid)
    pygame.display.flip()

我还从pygamehandle文件中使用了这些功能。

import pygame, standard

class load(object):

    pygame.init()

    def loadScreen(self, size, text, icon):

        pygame.display.set_caption(text, icon)
        pygame.display.set_icon(pygame.image.load(icon))

        screen = pygame.display.set_mode(size)

        self.screen = screen

        return screen

    def listImgLoad(self, list):

        img = []

        for i in range (0, len(list)):
            img.append(pygame.image.load(list[i]).convert())

        return img

    def blit(self, items, locations):

        for i in range (0, len(items)):
            self.screen.blit(items[i], locations[i])

    def grid(self, size, object):

        objects =[]
        locations = []

        x, y = size

        for xT in range (0, int(x / 20)):
            for yT in range(0, int(y / 20)):
                objects.append(object)
                locations.append((xT * 20, yT * 20))

        return objects, locations

更好的方法是为每个单元格创建一个Sprite类,如果该单元格是死的还是活着的,则将bool添加到deteermine中并相应地进行blit。

如果您熟悉Sprites,这里是文档 ,起初可能会令人困惑,但它们会帮助您制作更复杂的游戏,这也是指向我的《人生游戏》版本的链接

祝好运

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM