在期末考试结束后,我有一段时间没有真正从事编码工作。我决定写一个纸牌游戏回到编程现场。我只是想知道我错过了什么或者可以改进什么。
import random
suit_choices = ("Diamonds", "Hearts", "Clubs", "Spades")
suit_picked = random.choice(suit_choices)
number_picked = random.randint(2,9)
while True:
print suit_choices
user_card = raw_input('\nEnter a suit to pick from. Your choices are listed above. ').title()
if user_card == suit_picked:
print '\nYou guessed the suit type correct!'
user_number = input('\nNow pick a number card (2-9) ')
if user_number == number_picked:
print '\n You guessed the card number correct!'
break
else:
print '\nShucks. Try again.'
continue
else:
print '\nOH NO'
continue发布于 2014-06-07 11:20:20
有几件事我想说你现在失踪了:
目前,您的while True将永远运行。认为用户最终可能会感到无聊,这不是不合理的!因此,您可以添加如下内容:
if raw_input("Play again (y/n)? ").lower() == "n":
break到主回路的末尾。
如果用户输入一些不能eval的“卡号”,您的游戏就会崩溃。而且,他们可以输入一些不是西装的东西。正如@otus所指出的,您不应该使用input;我建议您添加更多的验证。这样的社区维基将对您有用,您最终应该会得到以下内容:
user_card = get_str_input('\nEnter a suit to pick from. Your choices are listed above. ',
suit_choices)
...
user_number = get_int_input('\nNow pick a number card (2-9) ', 2, 9)其中,这些函数只返回有效的输入并捕获任何相关的错误。
你在做游戏,为什么不告诉玩家他们做得如何?最简单的方法是:
right = wrong = 0然后+= 1每次通过循环得到适当的值。他们辞职后,表现如下:
print "You got {0} right and {0} wrong".format(right, wrong)
if right > wrong + 2:
print "Well done!"
elif right > wrong - 2:
print "Not bad"
else:
print "Bad luck"此外,纸牌游戏非常适合OOP;您可以使用Card、Deck和Game类,例如:
class Game(object):
def __init__(self, suits=None, faces=None):
if suits is None:
suits = ("Diamonds", "Hearts", "Clubs", "Spades")
if faces is None:
faces = range(2, 10)
self.suits, self.faces = suits, faces
self.deck = Deck(self.suits, self.faces)
self.deck.shuffle()
self.score = {'right': 0, 'wrong': 0}
def main_menu():
...
def _input_suit(self):
...
def _input_face(self):
...
...发布于 2014-06-07 07:54:53
continue
无论怎样,继续语句都会回到循环的末尾,因此它们是多余的。
user\_number = input('\nNow pick a number card (2-9) ')
在另一个地方,您正确地使用了raw_input。不同的是,input将给定的字符串作为表达式执行,这很少是您想要的(而且通常是不安全的)。
没什么别的了。所有字符串开头的\ns都有点难看,有些人更喜欢使用空打印语句来表示额外的空行。
https://codereview.stackexchange.com/questions/52677
复制相似问题