python中编写一个聪明版的尼姆游戏程序
时间: 2024-11-13 13:41:22 浏览: 24
在Python中编写一个聪明版的“石头、剪刀、布”(也称为“尼姆”游戏)程序,我们可以创建一个玩家和电脑对战的游戏。首先,我们需要定义一些规则,比如每次玩家和电脑都选择一种手势(石头、剪刀或布),然后判断胜负。以下是一个简单的示例:
```python
import random
def play_game():
options = ['rock', 'paper', 'scissors']
player_score = 0
computer_score = 0
while True:
print("Player's turn:")
player_choice = input("Choose rock, paper, or scissors: ").lower()
if player_choice not in options:
print("Invalid choice! Try again.")
continue
computer_choice = random.choice(options)
print(f"Computer chose {computer_choice}.")
if player_choice == computer_choice:
print("It's a tie!")
elif (player_choice == 'rock' and computer_choice == 'scissors') or \
(player_choice == 'paper' and computer_choice == 'rock') or \
(player_choice == 'scissors' and computer_choice == 'paper'):
print("Player wins!")
player_score += 1
else:
print("Computer wins!")
computer_score += 1
if player_score == 3 or computer_score == 3:
break
if player_score > computer_score:
print("Congratulations! Player wins the game!")
else:
print("Game over! Computer wins with a score of", computer_score.)
play_game()
```
在这个游戏中,玩家输入他们的选择,电脑随机生成一个选择。如果两者相同,则平局;如果按照“石头赢剪刀,剪刀赢布,布赢石头”的规则,判定胜者并更新分数。当一方累积达到3分时,游戏结束。
阅读全文