gpt4 book ai didi

python - 如何调试我的 Python 骰子游戏?

转载 作者:太空宇宙 更新时间:2023-11-03 14:39:23 24 4
gpt4 key购买 nike

所以我最近发布了一个我遇到问题的简单骰子程序的代码。它应该在一个数组中随机生成5个数字,然后检查是否有匹配的值,如果有,则添加到MATCH中,因此一旦完成检查,MATCH+1就是有多少个“同类”( match=1 表示两个相同,match=2 表示三个相同,依此类推)

它随机生成并正确显示数字,程序似乎检查没有错误,除非最后两个playerDice元素匹配,然后它抛出越界错误,为什么要这样做?而且,即使它运行时没有错误,它也不会真正显示最后一个打印行以及有多少个打印行,这是为什么?

这是代码:

import random
playerDice = [random.randint(1,6),random.randint(1,6),random.randint(1,6),random.randint(1,6),random.randint(1,6)]
compDice = [random.randint(1,6),random.randint(1,6),random.randint(1,6),random.randint(1,6),random.randint(1,6)]
match = 0
compmatch = 0

#print player dice
print("You rolled: ",end=" ")
a = 0
while a < len(playerDice):
print(str(playerDice[a]) + ", ",end=" ")
a = a + 1

#player check matches
i = 0
while i < len(playerDice):

j = i + 1
if playerDice[i] == playerDice[j]:
match = match + 1

while playerDice[i] != playerDice[j]:
j = j + 1
if playerDice[i] == playerDice[j]:
match = match + 1

i = i + 1

print("Player has: " + str(match + 1) + " of a kind.")

最佳答案

有一种更简单的方法来查找匹配:对骰子进行排序,然后查找重复的骰子。您可以手动查找这些运行,但标准库有一个函数:itertools.groupby 。这是一个简短的演示。

import random
from itertools import groupby

# Seed the randomizer while testing so that the results are repeatable.
random.seed(7)

def roll_dice(num):
return [random.randint(1,6) for _ in range(num)]

def find_matches(dice):
matches = []
for k, g in groupby(sorted(dice)):
matchlen = len(list(g))
if matchlen > 1:
matches.append('{} of a kind: {}'.format(matchlen, k))
return matches

for i in range(1, 6):
print('Round', i)

player_dice = roll_dice(5)
#comp_dice = roll_dice(5)

print('You rolled: ', end='')
print(*player_dice, sep=', ')

matches = find_matches(player_dice)
if not matches:
print('No matches')
else:
for row in matches:
print(row)
print()

输出

Round 1
You rolled: 3, 2, 4, 6, 1
No matches

Round 2
You rolled: 1, 5, 1, 3, 5
2 of a kind: 1
2 of a kind: 5

Round 3
You rolled: 1, 5, 2, 1, 1
3 of a kind: 1

Round 4
You rolled: 4, 4, 1, 2, 1
2 of a kind: 1
2 of a kind: 4

Round 5
You rolled: 5, 4, 1, 5, 1
2 of a kind: 1
2 of a kind: 5
<小时/>

这是 find_matches 的替代版本,它不使用 groupby。在纸上运行这个算法以确切了解它是如何工作的可能是个好主意。

def find_matches(dice):
matches = []
dice = sorted(dice)

prev = dice[0]
matchlen = 1
# Add a "dummy" entry so we can detect a group at the end of the list
for d in dice[1:] + [0]:
# Compare this die to the previous one
if d == prev:
# We're inside a run of matching dice
matchlen += 1
else:
# The previous run has ended, so see if it's
# long enough to add to the matches list
if matchlen > 1:
matches.append('{} of a kind: {}'.format(matchlen, prev))
# Reset the match length counter
matchlen = 1
# This die will be the previous die on the next loop iteration
prev = d

return matches

关于python - 如何调试我的 Python 骰子游戏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46653361/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com