Windows
时间: 2023-08-19 17:16:43 浏览: 36
好的,以下是 Python 代码实现石头剪刀布游戏的功能,以及将 Python 源文件打包为可执行文件的方法:
```python
import random
import os
import sys
# 定义手势和胜负关系
gestures = ['石头', '剪刀', '布']
win_relations = {'石头': '剪刀', '剪刀': '布', '布': '石头'}
# 定义游戏状态
player_score = 0
ai_score = 0
rounds = 0
# 游戏进行函数
def play_game():
global player_score, ai_score, rounds
# 玩家出手势
player_gesture = input('请出拳(石头/剪刀/布):')
while player_gesture not in gestures:
player_gesture = input('输入错误,请重新出拳(石头/剪刀/布):')
# AI 出手势
ai_gesture = random.choice(gestures)
print(f'AI 出了 {ai_gesture}')
# 判断胜负
if player_gesture == ai_gesture:
print('平局')
elif win_relations[player_gesture] == ai_gesture:
print('您赢了这局')
player_score += 1
else:
print('AI赢了这局')
ai_score += 1
# 更新游戏状态
rounds += 1
print(f'当前比分:您 {player_score}:{ai_score} AI')
# 判断游戏是否结束
if player_score >= 2:
print('您已经获得了胜利!')
return False
elif ai_score >= 2:
print('AI 获得了胜利!')
return False
else:
return True
# 游戏初始化函数
def init_game():
global player_score, ai_score, rounds
player_score = 0
ai_score = 0
rounds = 0
# 游戏主函数
def main():
print('欢迎来到石头剪刀布游戏!')
while True:
print(f'第 {rounds+1} 局游戏:')
if not play_game():
play_again = input('是否再来一局?(Y/N)')
if play_again.lower() == 'y':
init_game()
else:
break
# 打包为可执行文件
def build_executable():
if getattr(sys, 'frozen', False):
# 打包后的目录
bundle_dir = sys._MEIPASS
else:
# 源代码目录
bundle_dir = os.path.dirname(os.path.abspath(__file__))
# 生成可执行文件
os.system(f'pyinstaller --onefile {bundle_dir}/game.py')
if __name__ == '__main__':
main()
```
以上代码实现了石头剪刀布游戏的功能,并且可以将 Python 源文件打包为可执行文件。你只需要将以上代码保存为 `game.py` 文件,然后安装 `pyinstaller` 模块,使用以下命令进行打包:
```
pyinstaller --onefile game.py
```
打包完成后,在 `dist` 目录下会生成一个可执行文件 `game.exe`,双击即可运行游戏。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)