石头剪刀布的变体与项目 59“石头剪刀布”相同,只是玩家总是赢。选择计算机招式的代码被设置为总是选择失败的招式。你可以把这个游戏提供给你的朋友,他们赢的时候可能会很兴奋。。。一开始。看看他们需要多长时间才能意识到游戏被操纵对他们有利。
当您运行rockppapersscissorsalwayswin.py时,输出将如下所示:
Rock, Paper, Scissors, by Al Sweigart email@protected
- Rock beats scissors.
- Paper beats rocks.
- Scissors beats paper.
0 Wins, 0 Losses, 0 Ties
Enter your move: (R)ock (P)aper (S)cissors or (Q)uit
> p
PAPER versus...
1...
2...
3...
ROCK
You win!
1 Wins, 0 Losses, 0 Ties
Enter your move: (R)ock (P)aper (S)cissors or (Q)uit
> s
SCISSORS versus...
1...
2...
3...
PAPER
You win!
2 Wins, 0 Losses, 0 Ties
`--snip--`
SCISSORS versus...
1...
2...
3...
PAPER
You win!
413 Wins, 0 Losses, 0 Ties
Enter your move: (R)ock (P)aper (S)cissors or (Q)uit
`--snip--`你可能会注意到这个版本的程序比项目 59 要短。这是有意义的:当你不必为计算机随机生成一步棋并计算游戏的结果时,你可以从原始代码中删除相当多的代码。也没有变量来跟踪损失和平局的数量,因为无论如何这些都是零。
"""Rock,Paper, Scissors (Always Win version)
By Al Sweigart email@protected
The classic hand game of luck, except you always win.
This code is available at https://nostarch.com/big-book-small-python-programming
Tags: tiny, game, humor"""
import time, sys
print('''Rock, Paper, Scissors, by Al Sweigart email@protected
- Rock beats scissors.
- Paper beats rocks.
- Scissors beats paper.
''')
# These variables keep track of the number of wins.
wins = 0
while True: # Main game loop.
while True: # Keep asking until player enters R, P, S, or Q.
print('{} Wins, 0 Losses, 0 Ties'.format(wins))
print('Enter your move: (R)ock (P)aper (S)cissors or (Q)uit')
playerMove = input('> ').upper()
if playerMove == 'Q':
print('Thanks for playing!')
sys.exit()
if playerMove == 'R' or playerMove == 'P' or playerMove == 'S':
break
else:
print('Type one of R, P, S, or Q.')
# Display what the player chose:
if playerMove == 'R':
print('ROCK versus...')
elif playerMove == 'P':
print('PAPER versus...')
elif playerMove == 'S':
print('SCISSORS versus...')
# Count to three with dramatic pauses:
time.sleep(0.5)
print('1...')
time.sleep(0.25)
print('2...')
time.sleep(0.25)
print('3...')
time.sleep(0.25)
# Display what the computer chose:
if playerMove == 'R':
print('SCISSORS')
elif playerMove == 'P':
print('ROCK')
elif playerMove == 'S':
print('PAPER')
time.sleep(0.5)
print('You win!')
wins = wins + 1 在输入源代码并运行几次之后,尝试对其进行实验性的修改。你也可以自己想办法做到以下几点:
- 在游戏中加入“蜥蜴”和“斯波克”的招式。蜥蜴毒死斯波克,吃纸,却被石头碾碎,被剪刀斩首。斯波克折断剪刀,蒸发岩石,但被蜥蜴毒死,被纸证明是错误的。
- 允许玩家每赢一次就赢得一分。一旦获胜,玩家还可以承担“双倍或零”的风险,以可能赢得 2、4、8、16 以及更多的点数。
试着找出下列问题的答案。尝试对代码进行一些修改,然后重新运行程序,看看这些修改有什么影响。
- 如果删除或注释掉第 33 到 57 行会发生什么?
- 如果把第 22 行的
input('> ').upper()改成input('> ')会怎么样?
