1. 程式人生 > 其它 >【python學習1】編寫猜數字的小遊戲

【python學習1】編寫猜數字的小遊戲

跟著老師的課學習python哈哈~

#生成隨機數
# 模組moudule === 工具箱
#  匯入random
from time import sleep 

import random
#生成隨機數
n = random.randint(0,1000)

while True:
     m = int(input('please input a number\n'))
#m為獲取的使用者輸入數字,通過比較大小,給予使用者提示,從而繼續遊戲
     if m > n:
        print('too big')
     elif m < n:
        print('
too small') else: #猜到正確數字後,睡眠10秒,再自動退出程式 print('you win') sleep(10) break 

另外,我們把這個小遊戲匯出成可執行的exe程式

1、先下載 pyinstaller的安裝檔案,下載地址:http://www.pyinstaller.org/downloads.html

2、直接下載:pyinstaller 3.4

3、下載到本地後,直接解壓,然後通過管理員模式開啟命令視窗,用 cd命令切換至 pyinstaller的解壓路徑,然後執行 python setup.py install

4、安裝的過程會花點時間,就耐心等待吧,出現下面的提示表明安裝成功

---------------------------------------------------------------------------------------------------------------------

Best match: setuptools40.8.0

Adding setuptools40.8.0to easy-install.pthfile Installing easy_install-script.py script to C:\Program Files\Python3\Scripts
Installing easy_install.exe script to C:\Program Files\Python3\Scripts Installing easy_install-3.6-script.py script to C:\Program Files\Python3\Scripts Installing easy_install-3.6.exe script to C:\Program Files\Python3\Scripts Using c:\program files\python3\lib\site-packages Finished processing dependenciesforPyInstaller==3.4 --------------------------------------------------------------------------------------------------------------------- 5、通過 pip show pyinstaller檢視詳細資訊進一步確認安裝情況

---------------------------------------------------------------------------------------------------------------------

PS C:\Windows\system32> pip show pyinstaller

Name: pyinstaller Version:3.4 Summary: PyInstaller bundles a Python applicationandallits dependencies into a single package. Home-page: http://www.pyinstaller.org Author: Giovanni Bajo, Hartmut Goebel, David Vierra, David Cortesi, Martin Zibricky Author-email: [email protected] License: GPL license with a special exception which allows to use PyInstaller to buildanddistribute non-free programs (including commercial ones) Location: c:\program files\python3\lib\site-packages\pyinstaller-3.4-py3.6.egg Requires: setuptools, pefile, macholib, altgraph, pywin32-ctypes Required-by: --------------------------------------------------------------------------------------------------------------------- 6、用命令“pip install pywin32”安裝Pywin32,或者下載一個pywin32來安裝,注意檔案對應的Python版本。

7、cmd(或Power shell)進入py程式專案目錄,執行命令:pyinstaller -F -w --icon=xxx.ico main.py --noconsole。其中,-F表示生成單exe可執行檔案,-w表示窗體程式,
--icon是設定exe的顯示圖示,'main.py'是程式的入口,--noconsole 表示不展示cmd視窗,反過來想看cmd視窗就改成--console。

編譯:pyinstaller -F -w game.py (-F表示打包單個檔案,-w是為了開啟exe時候不彈出黑框)

設定exe的圖示:pyinstaller -F -w -i bitbug_favicon.ico game.py (-i用來設定編譯成exe檔案的圖示,後面跟.ico格式的圖片檔案)

我這一步這樣執行生成的exe執行是報錯的,報錯內容

Failed to execute script

經過百度以後,直接pyinstaller -F game.py ,不加-w,生成的小程式可以成功執行

在dist目錄下有個可執行的exe程式

這樣就可以開發出一個解悶的小遊戲了~哈哈

要有最樸素的生活和最遙遠的夢想,即使明日天寒地凍,山高水遠,路遠馬亡