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
109
110
111
112 | # 引入 Point 定義
from exercise1810 import Point
# 引入 Animal 定義
from exercise1811 import Animal
# 引入 Lion 定義
from exercise1812 import Lion
# 引入 print_world() 定義
from exercise2808 import print_world
# 引入 clear_monitor() 定義
from exercise2604 import clear_monitor
# 引入 move() 定義
from exercise2604 import move
# 引入 bound_check() 定義
from exercise2605 import bound_check
# 引入 examine_animal() 定義
from exercise2807 import examine_animal
# 引入 examine_animal_list() 定義
from exercise2808 import examine_animal_list
# 引入 examine_str() 定義
from exercise2804 import examine_str
# 從 exercise2201 引入 ParameterError
from exercise2201 import ParameterError
# 引入 time
import time
# 引入 os
import os
# 從 random 引入 randint
from random import randint
# 引入 copy
import copy
# 檢查移動座標是否有動物
def animal_check(original: Animal, animals: list, direction: str, world) -> str:
# 檢查參數是否正確的型態
if examine_animal(original) and examine_animal_list(animals) and examine_str(direction):
# 深度拷貝原始地圖
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 real_world[y - 1][x]
case "down":
if real_world[y + 1][x] != "口":
return real_world[y + 1][x]
case "right":
if real_world[y][x + 1] != "口":
return real_world[y][x + 1]
case "left":
if real_world[y][x - 1] != "口":
return real_world[y][x - 1]
return "口"
else:
raise ParameterError
# 執行部分
if __name__ == '__main__':
# 建立動物串列
animals = [Lion(Point(1,1), "Red"), Lion(Point(2,2), "Blue")]
# 設定地圖
world = [["口", "口", "口", "口"],
["口", "口", "口", "口"],
["口", "口", "口", "口"],
["口", "口", "口", "口"]]
try:
# 清空螢幕
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)
except:
print("遊戲建立過程中遭遇問題")
# 檔名: exercise2809.py
# 說明:《Python入門指南》的練習
# 網站: http://kaiching.org
# 作者: 張凱慶
# 時間: 2023 年 11 月
|