Python 焚塔游戲是一款基于 Python 編程語言開發的經典文字游戲。該游戲需要玩家通過不斷推導和策略調整,最終找到一條出口逃脫。下面,我們結合實例來介紹 Python 焚塔游戲的具體實現。
import random # 定義兩個全局變量 WIN_FLAG = False # 是否勝利 CONFIRMED_FLOORS = [] # 已確認樓層 def create_building(total_floors): """創建樓房,隨機指定一個樓層為出口""" exit_floor = random.randint(1, total_floors) print(f'[Info] The exit floor is No.{exit_floor}') return exit_floor def game_control(): """游戲開始""" print('Welcome to the Torch Tower game!') total_floors = input('Please enter the total number of floors in the building:') total_floors = int(total_floors) exit_floor = create_building(total_floors) # 玩家開始游戲 print(f'[Info] Starting from the top floor to the bottom floor, enter "y" if the torch is on, enter "n" if it is off:') for floor in range(total_floors, 0, -1): print(f'[Info] Is the torch on in No.{floor} floor: ', end='') answer = input().strip().lower() while answer not in ('y', 'n'): print(f'[Error] Invalid input, please try again.') answer = input().strip().lower() # 玩家已確認此樓層,將其添加到 CONFIRMED_FLOORS 數組中 CONFIRMED_FLOORS.append(floor) # 如果玩家回答錯誤或到達出口樓層,則游戲結束 if answer == 'n' or (answer == 'y' and floor == exit_floor): fail_or_win(answer) break def fail_or_win(answer): """玩家勝利或失敗""" if answer == 'y': print('[Info] Congratulations, you have escaped from the burning tower!') global WIN_FLAG WIN_FLAG = True else: print(f'[Info] Unfortunately, you fell from No.{CONFIRMED_FLOORS[-1]} floor and failed to escape from the building.') # 輸出已確認的樓層 print(f'[Info] The floors you have confirmed: {CONFIRMED_FLOORS}') if __name__ == '__main__': game_control()
游戲開始時,玩家需要輸入建筑總樓層數,并且隨機指定一個樓層為出口。隨后,玩家從頂層開始逐層作答,只能回答“是”或“否”,確認當前樓層的火炬是否點亮。如果回答錯誤或者到達出口樓層,則游戲結束。在游戲結束后,會對玩家是否勝利和已確認的樓層進行輸出。
上一篇c 循環封裝json數據
下一篇c 得到json數組對象