我已经确定了我在纸牌游戏中用于人工智能的代码,这些代码非常慢,并且在游戏处理过程中会挂起。问题是它是有效的,我想不出更好的方法。在没有进入游戏规则的情况下,我提供了一些有问题的代码以及一些上下文。
使用打印语句,我已经将有问题的代码范围缩小到sort_abs_list()。当打印出此函数时,会有长时间的停顿。
我是写代码的新手,欢迎任何建议。
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)
发布于 2017-02-07 00:02:55
因为您没有包含sort_abs_list_hand()的方法定义,所以很难准确地说出是什么原因导致速度变慢。
但。看起来你做了很多嵌套循环,并丢弃了一些中间结果。尝试在ai_grind_abs()中的循环之前将ai_grind()的结果保存在变量中,而不是在循环中调用它。您可以在abs_list_pile()循环之前对ai_grind_abs()的返回值执行相同的操作。
https://stackoverflow.com/questions/42071170
复制相似问题