Python: play it for fun
標籤:Python Introduction
光給字典一樣的教程不是很無聊嘛,不如一邊玩一邊學吧。
看完這篇部落格就可以完成一個小遊戲噢~ 下載安裝
鑒於 numpy 過幾年就要停止 python2 了,以後能用 python3 就用 3 不要猶豫。
在官網下載好對應版本安裝,windows 記得配一下環境變數。
在 linux 下不管尾碼名是不是 .py 都可以運行只要第一行加
#!/usr/bin/python
如果找不到 python 程式,就用 env 去找或者自己手動定位到程式的位置
#!/usr/bin/env python
寫代碼嘛,個人喜歡用 sublime,ctrl+b 編譯運行,但是輸入資料的時候會發現不行,可以去安裝外掛程式 SublimeREPL,預設 F5 可以運行,或者在 Preferences -> Key Binding 自行添加熱鍵
{ "keys":["f5"], "caption":"SublimeREPL:Python - RUN current file", "command":"run_existing_window_command","args": { "id":"repl_python_run", "file":"config/Python/Main.sublime-menu" }}
基本語句:wumpus hunt
既然學過C語言,話不多說,就看看Python的特別之處。下面是一個小遊戲:
#wumpus hunt v1.0from random import choicecave_numbers = range(1, 10)wumpus = choice(cave_numbers)print("Welcome! Darling! Here is ", len(cave_numbers), " caves")while True: your = input("input you position>") if (not your.isdigit()) or (int(your) not in cave_numbers): print("Not in any cave!") else: player = int(your) if wumpus == player: print("You win!") break elif wumpus == player+1 or wumpus == player-1: print("Smell the wumpus") else: print("Continue to guess!")
預設了目標位置,玩家輸入猜測的位置看能不能猜中。 in or not in
直接用 in 判斷是否是子串,在C語言裡還要調用函數 strstr 要煩一點。
True: "ab" in "abcde"False: not "ab" in "abcde"False: "xyz" in "abcde"True: not "xyz" in "abcde"True: "xyz" not in "abcde"
或和且 用 or and if while for
一開始容易忘了在這幾句話寫完以後要加 : ,不然肥腸容易報錯。 True False
注意首字母大寫,如上面代碼的第6行。 input()
python3 裡的輸入沒有 raw_input() 了,輸入預設都是字串類型,所以當輸入的是數字時注意強制轉換。如上面代碼的第8,11行。 加入管道地圖
對上面的遊戲做一些限制,設定聯通道路的約束
# wumpus hunt v2.0from random import choicecave_numbers = range(1, 10)wumpus = choice(cave_numbers)tunnel = [] # 新加入的管道地圖for i in range(10): t = [] while len(t) < 3: r = choice(cave_numbers) if r not in t: t.append(r) print(t) tunnel.append(t);print(tunnel)print("Welcome! Darling! Here is ", len(cave_numbers), " caves")player = wumpuswhile player == wumpus: player = choice(cave_numbers)while True: print("You're in cave ", player, " to choose") print(tunnel[player]) your = input("input you position>") if not your.isdigit(): print("Not a number") continue old_player = player player = int(your) if player not in tunnel[old_player]: # 稍作修改 print("Not in any cave!") player = old_player else: if wumpus == player: print("You win!") break elif wumpus == player+1 or wumpus == player-1: print("Smell the wumpus") else: print("Continue to guess!")
range()
表示自然數範圍: 若有三個參數,前兩個參數表示左閉右開的區間,第三個參數表示增量值 若有兩個參數,即第三個參數預設為1 當有單個參數時,即第一個參數預設為0
for x in range(2, 50, 6): print(x)==============================28142026323844
cave_numbers = range(1, 10) := [1, 10) = [1, 9] = {1,2,3,4,5,6,7,8,9}
range(3) := [0, 3) = [0, 2] = {0,1,2}
仔細看的話,上面的代碼的cave編號從1到9,但地圖卻有從0出發的路線,是多餘的安排。看在對運行沒影響,所以姑且不做處理。 list
可以放進不同類型元素(字串、數字、list等)的數組,且有很多簡便的操作
arraylist = ['mother', 'father', 45, 77]print(arraylist)arraylist.append(10) // 增加到末尾arraylist.remove(45) // 找到對應元素並刪除cut = arraylist[-2:] // 倒數第2個元素開始到末尾
下面有個詭異的地方,這裡Python變數不是傳統意義上的變數,實際上是指向記憶體的指標,所以
a = [10]b = aa[0] = 20print(b)a = 30print(b)================================[20][20]
可以將區間直接轉化到 list 放進去
arr = list(range(2, 50, 6))print(arr)=================================[2, 8, 14, 20, 26, 32, 38, 44]
坑人的地圖
隨機產生的地圖倒是很有可能出現不連通的情況,難不成讓玩家一直白忙活。還是一開始就寫好能愉快勝利的地圖吧。
# wumpus hunt v3.0 - tunneltunnel = []for x in range(10): tunnel.append([])visited = [1]unvisted = list(cave_numbers)unvisted.remove(1)while unvisted != []: x = choice(visited) if len(tunnel[x]) >= 3: continue y = choice(unvisted) tunnel[x].append(y) tunnel[y].append(x) visited.append(y) unvisted.remove(y)for t in tunnel: while len(t) < 3: v = choice(cave_numbers) if v not in t: t.append(v)print(tunnel)
這段地圖產生從1開始,慢慢加入未訪問過的點,產生雙向邊,得到完一副連通圖。為了讓條件更加豐富,再隨機加入一些單向邊。 封裝函數
有些代碼塊可以被替換成函數,使整個代碼看起來更加整潔。比如產生地圖的部分,以後也可以考慮新的產生辦法,只需要改動子函數就足夠了。
# wumpus hunt v4.0from random import choicedef create_tunnels(cave_numbers): tunnel = [] for x in range(10): tunnel.append([]) visited = [1] unvisted = list(cave_numbers) unvisted.remove(1) while unvisted != []: x = choice(visited) if len(tunnel[x]) >= 3: continue y = choice(unvisted) tunnel[x].append(y) tunnel[y].append(x) visited.append(y) unvisted.remove(y) for t in tunnel: while len(t) < 3: v = choice(cave_numbers) if v not in t: t.append(v) print(tunnel) return tunneldef follow_new_step(player): print("You're in cave ", player, " to choose") print(tunnel[player]) your = input("input you position>") if not your.isdigit(): print("Not a number") return -1; return int(your)cave_numbers = range(1, 10)wumpus = choice(cave_numbers)tunnel = create_tunnels(cave_numbers)player = wumpuswhile player == wumpus: player = choice(cave_numbers)print("Welcome! Darling! Here is ", len(cave_numbers), " caves")while True: old_player = player player = follow_new_step(player) if player not in tunnel[old_player]: print("Not in any cave!") player = old_player else: if wumpus == player: print("You win!") break elif wumpus == player+1 or wumpus == player-1: print("Smell the wumpus") else: print("Continue to guess!")
後續
考驗想象力的時刻到了,新功能和洞穴名字balabala請隨意添加修改……