马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
1. 在类中定义方法(函数)时, 需传入self参数, 作为类实例化后的唯一标志(地址指针), 在内部调用属性时, 要加上self. 例如: self.price
2. 隐藏类的属性和方法: 在属性和方法的前面加'__', 例如 __price = 100, def __init__(self): , 但实际上是改变了属性和方法的名字, 通过'__类名__变量名'还是可以访问到
3. __init__方法: 会在类实例化后自动调用, 可以重写这个方法, 为对象制定初始化方案
附 037动动手1 程序:
import random as r
legal_x = [0, 10]
legal_y = [0, 10]
class Turtle:
def __init__(self):
self.power = 100
self.x = r.randint(legal_x[0], legal_x[1])
self.y = r.randint(legal_y[0], legal_y[1])
def move(self):
new_x = self.x + r.choice([1, 2, -1, -2])
new_y = self.y + r.choice([1, 2, -1, -2])
if new_x < legal_x[0]:
new_x = legal_x[0] - ( new_x - legal_x[0] )
elif new_x > legal_x[1]:
new_x = legal_x[1] - ( new_x - legal_x[1] )
else:
self.x = new_x
if new_y < legal_y[0]:
new_y = legal_y[0] - ( new_y - legal_y[0] )
elif new_y > legal_y[1]:
new_y = legal_y[1] - ( new_y - legal_y[1] )
else:
self.y = new_y
self.power -= 1
return (self.x, self.y)
def eat(self):
self.power += 20
if self.power > 100:
self.power = 100
class Fish:
def __init__(self):
self.x = r.randint(legal_x[0], legal_x[1])
self.y = r.randint(legal_y[0], legal_y[1])
def move(self):
new_x = self.x + r.choice([1, -1])
new_y = self.y + r.choice([1, -1])
if new_x < legal_x[0]:
new_x = legal_x[0] - ( new_x - legal_x[0] )
elif new_x > legal_x[1]:
new_x = legal_x[1] - ( new_x - legal_x[1] )
else:
self.x = new_x
if new_y < legal_y[0]:
new_y = legal_y[0] - ( new_y - legal_y[0] )
elif new_y > legal_y[1]:
new_y = legal_y[1] - ( new_y - legal_y[1] )
else:
self.y = new_y
return (self.x, self.y)
turtle = Turtle()
fish = list()
for i in range(10):
new_fish = Fish()
fish.append(new_fish)
while True:
if not len(fish):
print('鱼儿被吃完了, 游戏结束')
break
if not turtle.power:
print('乌龟体力耗尽, 游戏结束')
break
pos = turtle.move()
for each_fish in fish:
if each_fish.move() == pos:
turtle.eat()
fish.remove(each_fish)
print("有一条鱼被吃掉了...")
|