我目前正在尝试在学校的计算机科学原理课上用python编写Uno代码,我创建了一个定义,从牌组中抽出卡片到玩家的手中,每当我运行代码时,我都会收到这个错误。我只是想知道如何修复它,因为我已经尝试了几种方法,但都没有结果。
我试着向玩家的手中添加物品(开始是空的)。我试过使用元组。我已经尝试过将绘图变量设置为列表。x规定了玩家的手牌,而y是他们抽出的牌的数量,而z是纸牌中的牌。
import random
import time
import sys
def draw_cards(x,y,z):
for q in range(y):
draw = random.choice(z)
x = x.insert(0,draw)
z = z.remove(draw)
return x,z
cards_in_deck = ["red 0","red 1", "red 2", "red 3", "red 4", "red 5","red 6","red 7", "red 8", "red 9", "red skip", "red reverse","red +2","wild","yellow 0","yellow 1", "yellow 2", "yellow 3", "yellow 4", "yellow 5","yellow 6","yellow 7", "yellow 8", "yellow 9", "yellow skip", "yellow reverse","yellow +2","wild","green 0","green 1", "green 2", "green 3", "green 4", "green 5","green 6","green 7", "green 8", "green 9", "green skip", "green reverse","green +2","wild","blue 0","blue 1", "blue 2", "blue 3", "blue 4", "blue 5","blue 6","blue 7", "blue 8", "blue 9", "blue skip", "blue reverse","blue +2","wild","red 1", "red 2", "red 3", "red 4", "red 5","red 6","red 7", "red 8", "red 9", "red skip", "red reverse","red +2","wild +4","yellow 1", "yellow 2", "yellow 3", "yellow 4", "yellow 5","yellow 6","yellow 7", "yellow 8", "yellow 9", "yellow skip", "yellow reverse","yellow +2","wild +4","green 1", "green 2", "green 3", "green 4", "green 5","green 6","green 7", "green 8", "green 9", "green skip", "green reverse","green +2","wild +4","blue 1", "blue 2", "blue 3", "blue 4", "blue 5","blue 6","blue 7", "blue 8", "blue 9", "blue skip", "blue reverse","blue +2","wild +4"]
player_hand = []
ai_dusty_hand = []
ai_cutie_hand = []
ai_smooth_hand= []
draw_cards(ai_dusty_hand,7,cards_in_deck)
draw_cards(ai_cutie_hand,7,cards_in_deck)
draw_cards(ai_smooth_hand,7,cards_in_deck)
draw_cards(player_hand,7,cards_in_deck)我期望的结果是每个玩家都有一个起始手,但是,输出以错误结束,
发布于 2019-04-02 00:50:39
Python中的列表是可变的。因此,当您操作列表时(即使在函数的作用域内),它将反映该列表被引用的所有位置。
x = x.insert(0,draw)
z = z.remove(draw)这些代码行分配列表中方法调用的返回值。这两个方法调用都不返回任何内容(因此它们返回None)。
删除函数中列表的赋值。
发布于 2019-04-02 00:47:06
问题来自这两行,因为remove不返回列表:
x = x.insert(0, draw)
z = z.remove(draw)insert和remove不返回任何内容。不要重新分配x和z,它应该可以工作:
x.insert(0, draw)
z.remove(draw)此外,您应该返回z来保存剩余的卡片:
def draw_cards(x,y,z):
for q in range(y):
draw = random.choice(z)
x.insert(0,draw)
z.remove(draw)
return z
cards_in_deck = draw_cards(ai_dusty_hand,7,cards_in_deck)
cards_in_deck = draw_cards(ai_cutie_hand,7,cards_in_deck)
cards_in_deck = draw_cards(ai_smooth_hand,7,cards_in_deck)
cards_in_deck = draw_cards(player_hand,7,cards_in_deck)https://stackoverflow.com/questions/55459783
复制相似问题