游戏:大鱼吃小鱼
游戏规则:
游戏编程:按照以下游戏编写一个乌龟类和鱼类,并尝试编写游戏。
假设游戏场景(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("------------有一条鱼被吃掉了!----------------")
**************胜者先胜而后求战,败者先战而后求胜!**************