一、引例--乌龟吃鱼
利用上一节课我们学到的知识,我们可以写一个简单的乌龟吃鱼的游戏,规则如下:
1、游戏背景为10*10的方格内
2、游戏开始自动生成10条鱼和一只乌龟
3、他们的移动方向是随机的
4、乌龟的最大移动能力是2,上下左右均可移动2格以内
5、鱼的最大移动能力为1,上下左右移动均为1格
6、当乌龟移动到边界时,自动反向移动
7、乌龟的初始体能为100,200为上限;每次移动需要消耗一点体力
8、当乌龟和鱼的坐标重合,代表乌龟把鱼吃掉,并且乌龟体力增加20
9、当乌龟没有体力值或鱼被吃光,则游戏结束
解析:练习上节课我们学习的知识,显然有乌龟和鱼两大类,在这两个类中他们各自有各自的行为(在类中我们也可以叫方法);现在有了最基本的思路,在乌龟的类中,他有----移动、判断是否越界、吃鱼;鱼具有的属性:-----移动,判断是否越界
有了上面的的思路我们就可以上手了。。。。。。
import random
class Turtle(object):
def __init__(self):
self.x = random.randint(1, 9) #划定边界范围为10*10
self.y = random.randint(1, 9)
self.power = 100
def move(self):
move_skill = [-1, 1, 0, -2, 2] #乌龟的移动能力只有这5中可能,
new_x = self.x + random.choice(move_skill) #新的x坐标=最初的+移动的随机值
new_y = self.y + random.choice(move_skill) #y同理
self.x = self.is_vaild(new_x) #判断新的坐标是否合法,在类中调用方法
self.y = self.is_vaild(new_y)
self.power -= 1 #每移动一次体力值箭1
def is_vaild(self, point): #判断坐标是否还在边界内,如果超出则需要反转
if point <0:
return 0 - point
elif point >9:
return 9 - (point - 9)
return point
def eat(self): #每吃掉一条鱼就可以增加20体力,200为上限
self.power += 20
if self.power >=200:
self.power = 200
class Fish(object):
def __init__(self):
self.x = random.randint(1, 9)
self.y = random.randint(1, 9)
def move(self):
move_skill = [-1, 1, 0]
new_x = self.x + random.choice(move_skill)
new_y = self.y + random.choice(move_skill)
self.x = self.is_vaild(new_x)
self.y = self.is_vaild(new_y)
def is_vaild(self,point):
if point <0:
return 0 - point
elif point >9:
return 9 - (point - 9)
return point
d