热线电话:13121318867

登录
2019-03-08 阅读量: 644
python如何将代码转换为库(5)

现在,如果程序员想要改变大小,他们可以,否则他们不必。我们可能还希望允许程序员修改blob的速度,如果他们想:

import random


class Blob:

def __init__(self, color, x_boundary, y_boundary, size_range=(4,8), movement_range=(-1,2)):
self.size = random.randrange(size_range[0],size_range[1])
self.color = color
self.x_boundary = x_boundary
self.y_boundary = y_boundary
self.x = random.randrange(0, self.x_boundary)
self.y = random.randrange(0, self.y_boundary)
self.movement_range = movement_range

def move(self):
self.move_x = random.randrange(self.movement_range[0],self.movement_range[1])
self.move_y = random.randrange(self.movement_range[0],self.movement_range[1])
self.x += self.move_x
self.y += self.move_y

if self.x self.x_boundary: self.x = self.x_boundary

if self.y self.y_boundary: self.y = self.y_boundary

我们强制blob保持入界的线。可能有一些例子我们希望blob能够在视野中自由漫游吗?当然!这个边界代码有用吗?程序员是否可能想要经常使用它?当然!但是,要么根本没有代码,要么给它自己的方法更有意义,如下所示:

import random

class Blob:

def __init__(self, color, x_boundary, y_boundary, size_range=(4,8), movement_range=(-1,2)):
self.size = random.randrange(size_range[0],size_range[1])
self.color = color
self.x_boundary = x_boundary
self.y_boundary = y_boundary
self.x = random.randrange(0, self.x_boundary)
self.y = random.randrange(0, self.y_boundary)
self.movement_range = movement_range

def move(self):
self.move_x = random.randrange(self.movement_range[0],self.movement_range[1])
self.move_y = random.randrange(self.movement_range[0],self.movement_range[1])
self.x += self.move_x
self.y += self.move_y

def check_bounds(self):
if self.x self.x_boundary: self.x = self.x_boundary

if self.y self.y_boundary: self.y = self.y_boundary
6.9776
1
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子