简体   繁体   中英

slow indexing function for A.I. hanging game

I have identified code I use for AI in my card game that is very slow and hangs the game while it's processing. The problem is it works and I can't figure out a better way of doing it. Without getting into the rules of the game I've provided the problematic code along with a little context.

Using print statements I've narrowed down the problematic code to sort_abs_list(). When printing out this function there is a long pause.

I'm new to writing code any suggestions are welcome.

values_list = [[9, 3, 10, 5, 2], [0, -6, 1, -4, -7], [8, 2, 9, 4, 1], 
[0, -6, 1, -4, -7], [9, 3, 10, 5, 2]]
number_needed_for_20 = -1
ai hand = [10, 1, 9, 10]
ai_piles = [1, 7, 0, 5, 8]

def ai_grind():                                               
    """Creates a 2D list of values using the number needed for twenty"""
    list = []
    for x in range(5):
        list.append([])
        for y in range(5):
            list[x].append(values_list[x][y] - (number_needed_for_20))
    return list

def ai_grind_abs():                                                        
    """Returns a 2D list of absolute values that will be indexed"""
    list = []
    for x in range(5): 
        list.append([])
        for y in range(5):
            list[x].append(abs(ai_grind()[x][y]))
    return list

def abs_list_pile():      
    """Returns pile positions of the min values"""
    list = []
    for x in range(5):
        list.append(ai_grind_abs()[x].index(min(ai_grind_abs()[x])))
    return list

def abs_list_hand():
    """A list of min values for hand position"""
    list = []
    for x in range(5): 
        list.append(min(ai_grind_abs()[x]))
    return list

def sort_abs_list(): # problematic                               
    """Returns position of pile and hand cards"""
    # finds hand position
    a = abs_list_hand().index(min(sort_abs_list_hand()))
    # finds pile position
    b = abs_list_pile()[a]

def ai_hand_to_pile():
    """Moves a card from the hand to the pile"""
    card = ai_hand[sort_abs_list()[0]]
    ai_piles[sort_abs_list()[1]].append(card)
    ai_hand.remove(card)

Since you didn't include the method definition for sort_abs_list_hand() it's hard to say exactly what's causing the slowness.

But. It seems you're doing a lot of nested looping, and throwing away some intermediate results. Try saving the result for ai_grind() in a variable before the loop in ai_grind_abs(), instead of calling it inside the loop. You can do the same for the return value of ai_grind_abs() before the loop of abs_list_pile().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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