Python 入門指南 5.0
exercise2906.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 | # 引入 Point 定義 from exercise1810 import Point # 引入 Lion 定義 from exercise1812 import Lion # 引入 Elephant 定義 from exercise2901 import Elephant # 引入 Cat 定義 from exercise2902 import Cat # 引入 Mouse 定義 from exercise2903 import Mouse # 引入 examine_animal_list() 定義 from exercise2808 import examine_animal_list # 引入 clear_monitor() 定義 from exercise2604 import clear_monitor # 引入 move() 定義 from exercise2807 import move # 引入 bound_check() 定義 from exercise2605 import bound_check # 引入 animal_check() 定義 from exercise2809 import animal_check # 引入 time import time # 引入 os import os # 引入 copy import copy # 從 random 引入 randint from random import randint # 從 random 引入 choice from random import choice # 取得地圖字串的函數 def get_world_string(animals: list, world: list): # 檢查參數是否正確的型態 if examine_animal_list(animals): # 深度拷貝原始地圖 real_world = copy.deepcopy(world) # 在新地圖上加入動物 for animal in animals: # 取得動物座標 x = animal.point.x y = animal.point.y # 在地圖上置換成動物名稱 i = 0 while i < len(real_world): j = 0 while j < len(real_world[i]): if i == y and j == x: real_world[i][j] = animal.name j += 1 i += 1 # 建立地圖字串 result = "" for row in real_world: for column in row: result += column + " " result += "\n" # 回傳結果 return result else: raise ParameterError # 產生遊戲結果字串 def generate_result(): # 建立動物串列 animals = {"象":Elephant(Point(0,0), "象"), "獅":Lion(Point(0,3), "獅"), "鼠":Mouse(Point(3,0), "鼠"), "貓":Cat(Point(3,3), "貓")} # 設定地圖 world = [["口", "口", "口", "口"], ["口", "口", "口", "口"], ["口", "口", "口", "口"], ["口", "口", "口", "口"]] # 設定移動指令 direction = ["up", "down", "right", "left"] # 移動的迴圈 while len(animals) > 1: animal = choice(list(animals.values())) clear_monitor() d = direction[randint(0, 3)] if bound_check(animal, d, world): other = animal_check(animal, list(animals.values()), d, world) if other == "口": move(animal, d) else: if other in animal.food: animals.pop(other) move(animal, d) else: animals.pop(animal.name) yield get_world_string(list(animals.values()), world) else: continue # 執行部分 if __name__ == '__main__': # 遊戲模擬迴圈 for game_string in generate_result(): # 清空螢幕 clear_monitor() # 印出 print(game_string) # 暫停 0.4 秒 time.sleep(0.4) # 檔名: exercise2906.py # 說明:《Python入門指南》的練習 # 網站: http://kaiching.org # 作者: 張凱慶 # 時間: 2023 年 11 月 |