首页 > 代码库 > 练习:类 乌龟吃鱼小游戏

练习:类 乌龟吃鱼小游戏

1:场景范围(x,y)  0<=x<=10,  0<=y<=10

2:游戏生成1只乌龟和10只小鱼

3:移动方向随机

4:乌龟的最大移动能力是2,(可以随机选择移动距离是1还是2),鱼儿的最大移动能力是1

5:移动到边缘时,自动反方向移动

6:乌龟初始化体力为1,每移动一次消耗1,鱼儿没有体力

7:当乌龟和鱼儿坐标重合时,鱼儿被乌龟吃掉,体力增长20

8:乌龟体力为0时,乌龟挂掉。或者鱼儿数量为0时,游戏结束

 

 1 import random as r
 2 
 3 legal_x=[0,10]
 4 legal_y=[0,10]
 5 
 6 class Turtle:
 7     def __init__(self): #构造器,实例对象创建时调用
 8         #初始体力
 9         self.power=100
10         #初始化位置
11         self.x=r.randint(legal_x[0],legal_x[1])
12         self.y=r.randint(legal_y[0],legal_y[1])
13 
14     def move(self):
15         #随机计算方向并移动到新的位置
16         new_x=self.x + r.choice([1 , 2 , -1 , -2])  #随机选择移动距离
17         new_y=self.y + r.choice([1 , 2 , -1 , -2])
18 
19         #检查x是否超出场景
20         if new_x < legal_x[0]:
21             self.x = legal_x[0]-(new_x-legal_x[0])
22         elif new_x > legal_x[1]:
23             self.x = legal_x[1] - (new_x-legal_x[1])
24         else:
25             self.x = new_x
26             
27         #检查y是否超出场景
28         if new_y < legal_y[0]:
29             self.y = legal_y[0] - ( new_y-legal_y[0])
30         elif new_y > legal_y[1]:
31             self.y = legal_y[1] - (new_y - legal_y[1])
32         else:
33             self.y = new_y
34 
35         self.power -= 1
36         return (self.x,self.y)
37         
38     def eat(self):
39         self.power+=20
40         if self.power>100:
41             self.power=100
42         print(turtle.power)
43     
44 class Fish:
45     def __init__(self):
46         self.x=r.randint(legal_x[0],legal_x[1])
47         self.y=r.randint(legal_y[0],legal_y[1])
48 
49     def move(self):
50         new_x=self.x + r.choice([1,-1])
51         new_y=self.y + r.choice([1,-1])
52         #检查x是否超出场景
53         if new_x < legal_x[0]:
54             self.x = legal_x[0]-(new_x-legal_x[0])
55         elif new_x > legal_x[1]:
56             self.x = legal_x[1] - (new_x-legal_x[1])
57         else:
58             self.x = new_x
59             
60         #检查y是否超出场景
61         if new_y < legal_y[0]:
62             self.y = legal_y[0] - ( new_y-legal_y[0])
63         elif new_y > legal_y[1]:
64             self.y = legal_y[1] - (new_y - legal_y[1])
65         else:
66             self.y = new_y
67 
68         return (self.x , self.y)    
69 
70 turtle = Turtle()
71 fish = []
72 
73 for i in range(10):
74     new_fish=Fish()
75     fish.append(new_fish)
76 while True:
77     if not len(fish):
78         print("鱼儿都吃光啦,游戏结束!")
79         break
80     if not turtle.power:
81         print("乌龟的体力耗尽,挂掉了")
82         break
83     pos = turtle.move()
84     for each_fish in fish[:]:
85         if each_fish.move() == pos:
86             #鱼儿被吃掉
87             turtle.eat()
88             fish.remove(each_fish)
89             print("有条鱼儿被吃掉了,还剩%d条" % len(fish))

 

练习:类 乌龟吃鱼小游戏