1. 程式人生 > >遊戲:大魚吃小魚

遊戲:大魚吃小魚

and tortoise 結束 編程 post == physical pri --

遊戲規則:

遊戲編程:按照以下遊戲編寫一個烏龜類和魚類,並嘗試編寫遊戲。
假設遊戲場景(x,y)為0<=x<=10,0<=y<=10
遊戲生成1只烏龜和10只魚
他們的移動方向均隨機
烏龜的最大移動速度為2,它可以隨機選擇1還是2移動,魚兒的最大移動能力是1
當移動到最大邊界時,自動反方向移動
烏龜初始化體力為100(上限)
烏龜每移動一次,體力消耗1
當烏龜和魚坐標重疊,烏龜吃掉魚,烏龜體力增加20
魚不考慮體力
當烏龜體力為0或者魚兒的數量為0時遊戲結束

代碼:

  1 import random as r
  2 
  3 # from random import choice
  4 # 定義邊界
5 boundary_x = [0, 10] 6 boundary_y = [0, 10] 7 8 9 # 定義烏龜類 10 class Tortoise: 11 def __init__(self): 12 13 # count=1 14 self.physical_power = 100 15 self.x = r.randint(boundary_x[0], boundary_x[1]) 16 self.y = r.randint(boundary_y[0], boundary_y[1]) 17
18 def move(self): 19 # 隨機選擇移動速度和移動方向 20 new_x = self.x + r.choice([1, 2, -1, -2]) 21 new_y = self.y + r.choice([1, 2, -1, -2]) 22 # print("烏龜當前坐標是:",self.x,self.y) 23 # print("烏龜當前速度是:",self.speed) 24 # 當移動到X軸最大邊界時,自動反方向移動 25 if new_x > boundary_x[1]:
26 self.x = boundary_x[1] - (new_x - boundary_x[1]) 27 elif new_x < boundary_x[0]: 28 self.x = boundary_x[0] - (new_x - boundary_x[0]) 29 else: 30 self.x = new_x 31 32 # 當移動到Y軸最大邊界時,自動反方向移動 33 if new_y > boundary_y[1]: 34 self.x = boundary_y[1] - (new_y - boundary_y[1]) 35 elif new_y < boundary_y[0]: 36 self.y = boundary_y[0] - (new_y - boundary_y[0]) 37 else: 38 self.y = new_y 39 40 # 體力消耗加1 41 self.physical_power -= 1 42 43 return (self.x, self.y) 44 45 def eat(self): 46 self.physical_power += 20 # 體力增加20 47 if self.physical_power > 100: 48 self.physical_power = 100 49 50 51 class Fish: 52 def __init__(self): 53 54 # count=10 55 self.x = r.randint(boundary_x[0], boundary_x[1]) 56 self.y = r.randint(boundary_y[0], boundary_y[1]) 57 # 設置移動速度 58 # speed = 1 59 60 def move(self): 61 # 隨機選擇移動速度和移動方向 62 new_x = self.x + r.choice([1, -1]) 63 new_y = self.y + r.choice([1, -1]) 64 # 當移動到X軸最大邊界時,自動反方向移動 65 if new_x > boundary_x[1]: 66 self.x = boundary_x[1] - (new_x - boundary_x[1]) 67 elif new_x < boundary_x[0]: 68 self.x = boundary_x[0] - (new_x - boundary_x[0]) 69 else: 70 self.x = new_x 71 72 # 當移動到Y軸最大邊界時,自動反方向移動 73 if new_y > boundary_y[1]: 74 self.x = boundary_y[1] - (new_y - boundary_y[1]) 75 elif new_y < boundary_y[0]: 76 self.y = boundary_y[0] - (new_y - boundary_y[0]) 77 else: 78 self.y = new_y 79 80 return (self.x, self.y) 81 82 83 fish = [] 84 tor = Tortoise() 85 for i in range(10): 86 new_fish = Fish() 87 fish.append(new_fish) 88 89 while 1: 90 if len(fish) == 0: 91 print("魚兒都被吃光了,遊戲結束!") 92 break 93 if tor.physical_power == 0: 94 print("烏龜體力耗完了,遊戲結束!") 95 break 96 97 pos = tor.move() 98 print("烏龜坐標是:", pos) 99 for each_fish in fish[:]: 100 f = each_fish.move() 101 print("魚兒坐標是: ", f) 102 if f == pos: 103 tor.eat() 104 fish.remove(each_fish) 105 print("------------有一條魚被吃掉了!----------------")

遊戲:大魚吃小魚