Python 入門指南 5.0
exercise2608.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 | # 引入 Point 定義 from exercise1810 import Point # 引入 Lion 定義 from exercise1812 import Lion # 引入 print_world() 定義 from exercise2607 import print_world # 引入 clear_monitor() 定義 from exercise2604 import clear_monitor # 引入 move() 定義 from exercise2604 import move # 引入 bound_check() 定義 from exercise2605 import bound_check # 引入 time import time # 引入 os import os # 從 random 引入 randint from random import randint # 引入 copy import copy # 檢查移動座標是否有動物 def animal_check(original, animals, direction, world): # 深度拷貝原始地圖 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 # 取得當前動物座標 x = original.point.x y = original.point.y # 回傳結果 match direction: case "up": if real_world[y - 1][x] != "口": return False case "down": if real_world[y + 1][x] != "口": return False case "right": if real_world[y][x + 1] != "口": return False case "left": if real_world[y][x - 1] != "口": return False return True # 執行部分 if __name__ == '__main__': # 建立動物串列 animals = [Lion(Point(1,1), "Red"), Lion(Point(2,2), "Blue")] # 設定地圖 world = [["口", "口", "口", "口"], ["口", "口", "口", "口"], ["口", "口", "口", "口"], ["口", "口", "口", "口"]] # 清空螢幕 clear_monitor() # 顯示初始位置 print_world(animals, world) # 暫停一秒 time.sleep(1) # 設定移動指令 direction = ["up", "down", "right", "left"] # 移動的迴圈 for i in range(10): for animal in animals: clear_monitor() d = direction[randint(0, 3)] if bound_check(animal, d, world): if animal_check(animal, animals, d, world): move(animal, d) else: print("有阻礙") else: print("撞牆中") print_world(animals, world) time.sleep(1) # 檔名: exercise2608.py # 說明:《Python入門指南》的練習 # 網站: http://kaiching.org # 作者: 張凱慶 # 時間: 2023 年 10 月 |