如何简化我的 python 乌龟游戏,以避免它随着 运行 时间的增加而占用更大的内存?

How can I simplify my python turtle game to avoid it from taking larger memory as the running time increases?

这是一款基于python海龟模块的翻色游戏。 该游戏由一个矩形板组成,该板被分成许多不同颜色的平面彩色瓷砖。游戏的目标是通过选择棋盘上的一个方块然后将其颜色更改为另一种颜色,将所有方块变成相同的颜色。新选择的颜色将扩散到与所选瓷砖的原始颜色相匹配的所有相邻瓷砖。玩家继续选择另一个牌并将其颜色更改为另一种颜色,直到棋盘内的所有牌都翻转为相同的颜色。除了矩形板之外,板下方还显示了一系列颜色。这些是玩家可以选择翻转所选方块颜色的颜色。

当我开始运行我的游戏时,随着运行宁时间的增加,它占用的内存越来越大。而且越来越慢。我认为这可能是由于我的代码末尾的 while 循环。但我不确定。我怎样才能修改它以使其更快?

from turtle import *
from random import choice
from functools import partial

# set game dimension to be 5 x 5
g_dim = 5
# use random.choice() to create the color for the game
g_game = [choice(['#0000FF', '#FF0000', '#FFFF00', '#008000', '#00FFFF']) for i in range(25)]
# provide the option to flip during the game
optionColor = ['#0000FF', '#FF0000', '#FFFF00', '#008000', '#00FFFF']

# show a set of colors as option for user to flip
def promptColorToFlip(optionColor,  # a list that contains a set of the color for user to choose from
                    height=100,     # the height of the option tiles
                    width=100       # the width of the option tiles
                    ):
    # the coordinates of the first tiles
    x = -200
    y = -200

    for i in range(len(optionColor)):
        tile = prototype.clone()
        tile.goto(i * width + x, -(height+50) + y)
        tile.color('white', optionColor[i])
        tile.onclick(partial(returnChosenColor, i))

# return the index of the select-to-flip-to color in the optionColor list
def returnChosenColor(userChosenColor,  # the index of the select-to-flip-to color in the optionColor list
                        x, y            # take the positional arguments from the onclick() function to avoid errors, no significant meaning
                        ):
    global userOption
    userOption = userChosenColor

def refreshScreen(game, rows=5, columns=5, height=100, width=100):
    x = -200  
    y = -200

    for column in range(columns):
        for row in range(rows):
            square = prototype.clone()
            square.goto(column * (5+width) + x , row * (5+height) + y)
            square.onclick(partial(userChosenTile, row, column))
            if state['framed'] == row*5+column:
                square.color('black', game[row*5+column])
            else:
                square.color('white', game[row*5+column])
    update()

def userChosenTile(ROW, COL, x, y):
    global state, R, C
    state['framed'] = ROW*5+COL
    R = ROW
    C = COL

def flipColor(row, col, game, orig, to):
    print('excuted')
    global userOption, state, R, C
    if orig == to:
        return game
    if row < 0 or row >= g_dim:
        return
    if col < 0 or col >= g_dim:
        return

    idx = row*g_dim+col   

    if game[idx] != orig:
        return
    print(idx, 'excuted')
    game[idx] = to
    flipColor(row-1, col, game, orig, to)
    flipColor(row+1, col, game, orig, to)
    flipColor(row, col-1, game, orig, to)
    flipColor(row, col+1, game, orig, to)
    
    state = {'framed':None}
    R = None
    C = None
    userOption = None

    return game

# initialize the game status
state = {'framed':None}     # stores the number of the last selected tile, which will be framed with a black border
R = None                    # the row of the last selected tile
C = None                    # the column of the last selected tile
userOption = None           # the index of the select-to-flip-to color in the optionColor list

# create a prototype of the tiles
prototype = Turtle()
prototype.shape('square')
prototype.shapesize(5, 5, 5)
prototype.penup()

# disable auto screen refresh
tracer(False)
# run the game
while True:
    # the try and except block here is to prevent error from raising when user terminate the progarm
    try:
        promptColorToFlip(optionColor)
        refreshScreen(g_game)
        if state['framed'] is not None and R is not None and C is not None and userOption is not None:
            g_game = flipColor(R, C, g_game, g_game[state['framed']], optionColor[userOption])
    except:
        pass

我还没有完全研究过您有些复杂的代码,但我很确定我看到了游戏运行一段时间后逐渐变慢的根源。它就在这里,在您的 refreshScreen 函数中:

for column in range(columns):
    for row in range(rows):
        square = prototype.clone()
        ...

此代码在每一帧上为棋盘的每个方格制作一只新海龟。那些海龟永远不会消失,所以你只能不断地堆积越来越多的海龟,随着时间的推移,这会降低整个游戏的性能。解决方案可能是每个位置只使用一只海龟,并保留对它们的引用,以便您可以在必要时更改它们的颜色,而不是每次都重新制作它们。