python编程设计一个剪刀石头布游戏
时间: 2024-09-29 22:09:30 浏览: 60
Python石头剪刀布游戏编程教程
在Python中设计一个简单的剪刀、石头、布游戏,可以遵循以下步骤:
1. **创建玩家选择函数**:
```python
def player_choice():
choices = ["石头", "剪刀", "布"]
return input("请输入你的选择(石头、剪刀、布):").lower().strip() in choices
```
2. **创建电脑选择函数**:
```python
import random
def computer_choice():
return random.choice(["石头", "剪刀", "布"])
```
3. **游戏规则判断函数**:
```python
def compare_choices(player, computer):
if player == computer:
return "平局"
elif (player == "石头" and computer == "剪刀") or \
(player == "剪刀" and computer == "布") or \
(player == "布" and computer == "石头"):
return "你赢了!"
else:
return "电脑赢了!"
```
4. **主循环**:
```python
while True:
player_win = False
player_choice_str = player_choice()
print(f"你选择了 {player_choice_str},电脑选择...")
computer_choice_str = computer_choice()
result = compare_choices(player_choice_str, computer_choice_str)
print(result)
if "你赢了!" in result or "电脑赢了!" in result:
player_win = True
break
if player_win:
print("恭喜你赢得了这场比赛!")
else:
print("很遗憾,你输了。")
```
5. **结束游戏提示**:
添加一些游戏结束的条件,如用户请求退出,或者达到一定的胜利次数等。
完整代码示例:
```python
def main():
# ... (以上所有代码段)
if __name__ == "__main__":
main()
```
阅读全文