与许多关于这个话题的问题不同,我的不是作业。我已经构建了一个工作的Ghost机器人。我最终的目标是作为一个爱好构建一个扑克机器人,但Ghost游戏似乎是一个更容易开始思考的游戏。
我提问的代码如下:
def computer_prompt(playerName,word_string): length_string = len(word_string) for possibilities in wordlist: if possibilities[:length_string].lower() == word_string: if len(possibilities) > 3 and len(possibilities) % 2 != 0: if check_game.is_valid_word(possibilities[length_string],wordlist): if not check_game.word_formed(possibilities[:length_string + 1],wordlist): print(possibilities) return possibilities[:length_string + 1]
目前,我只是希望电脑总是第二个出招,人类总是先出招。问题是,虽然电脑几乎每次都能打败我,但有几次我仍然可以智胜它。例如,如果我玩“h”,然后它玩“a”,然后我玩“z”,然后它又玩“a”,然后我玩“r”,然后它抛出一个错误(因为它不承认失败 :))。
我该如何修改它,使它在这种情况下知道在我玩“z”之后不要说“a”?显然,我可以将这个例子编码为一个例外,但我想知道解决这个问题的通用方法。一般来说,现在电脑打败我是因为它会寻找所有可能的单词列表,这些单词会在它决定选择哪个字母之前结束在我身上。但在“hazard”这个例子中,它只是卡住了,我希望它能提前几步知道它会卡住,这样它就不会陷入这种境地…
非常感谢!
添加于9/27
对于任何感兴趣的人,以下代码似乎比我之前的要好一些。尽管还不完美…:
def all_possibilities(word_string, length_string): possibilities = [] for possibility in wordlist: if possibility[:length_string].lower() == word_string: possibilities.append(possibility) return possibilitiesdef clear_loser(possibilities): clear_losers = [] for item in possibilities: if len(item) % 2 == 0: clear_losers.append(item) return clear_losersdef first_n_letters(sub_optimal_computer_possibilities, length_string): first_n_Letters = [] for item in sub_optimal_computer_possibilities: first_n_Letters.append(item[:length_string + 1]) return list(set(first_n_Letters))def existing_Optimal_Move(FIRSTNLETTERS,first_letters_of_clear_losers): length_sub_opt_list = len(FIRSTNLETTERS) new_list = [] for item in FIRSTNLETTERS: if not item in first_letters_of_clear_losers: new_list.append(item) return new_listdef computer_prompt(word_string): length_string = len(word_string) possibilities = all_possibilities(word_string, length_string) clear_losers = clear_loser(possibilities) #创建将在电脑上结束的单词列表 sub_optimal_computer_possibilities = [x for x in possibilities if x not in clear_losers] #创建将在人类上结束的单词列表(包括可能对我不利但聪明的人类会使它在我之前结束的单词) FIRSTNLETTERS = first_n_letters(sub_optimal_computer_possibilities, length_string) first_letters_of_clear_losers = first_n_letters(clear_losers, length_string) optimalMove = existing_Optimal_Move(FIRSTNLETTERS, first_letters_of_clear_losers) if optimalMove: print("OPTIMAL MOVE") for item in optimalMove: #print(optimalMove) return item[:length_string + 1] else: for item in FIRSTNLETTERS: #print(FIRSTNLETTERS) return item[:length_string + 1]
回答:
查看三元搜索树数据结构:http://en.wikipedia.org/wiki/Ternary_search_tree
你可以从你的单词列表中构建一个三元搜索树。然后,你可以让电脑循环遍历树中当前位置的子节点。它将消除任何输的移动(一个字母选择没有子节点),然后遍历所有它们的子节点。如果电脑的任何可能移动都有所有输的子节点(它们自己没有子节点),那么它将选择那个选择,因为它保证获胜。
在循环过程中,它将消除任何保证输的移动。如果它没有剩余的移动,这意味着每个移动都会导致它输,所以它将随机选择字母直到输。否则,它将选择移动,这个移动有最少可能的输法,或者最多的赢法,可能是一个线性组合,带有实验确定的常数。你需要聪明的循环或递归函数。
最后,如果你想让他使用机器学习,你可能想要一个字典,比如memory = {}
,然后每次他玩并且输了,他会将他的选择列表添加到记忆中,并在下次避免这种模式。他也可以通过这种方式调整常数。为了保持记忆,你应该将其保存到文件中或使用Python的pickle模块进行序列化。