|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- 课堂笔记:
- 1. self:
- a. self把对象名传进类里,访问类里的数据
- 2. 公有,私有:
- a. 类里的属性和方法都是公有的
- b. 私有变量用__变量名定义,对象名.__私有变量名访问,或对象名._类名__私有变量名
- 3. __init()__方法,被称作魔法方法.在类里定义一个init方法,那么就可以在实例化的时候,对对象进行初始化.
- 测试题:
- 0.
- 封装
- 多态,对同一类不同对象调用不同方法,产生不同结果.
- 1.
- 继承,class A(class B):pass,这时候A就继承了B类,A就是B的子类.
- 2.
- 把类的对象传入类中做运算.
- 3.
- 在属性或方法前面加__.
- 4.
- __init__方法.
- 5.
- 定义了一个参数self,但是没用这个参数.去掉self就好了.
- 动动手:
- 0.
- import random
- class Turtle:
-
- health = 100
- x = random.randint(0,10)
- y = random.randint(0,10)
- direction = random.randint(1,4)
- def moveUp(self):
- y += random.randint(1,2)
- if self.y >= 10:
- self.moveDown()
- def moveDown(self):
- y -= random.randint(1,2)
- if self.y <= 0:
- self.moveUp(self)
- def moveRight(self):
- x += random.randint(1,2)
- if self.x >= 10:
- self.moveLeft()
- def moveLeft(self):
- x -= random.randint(1,2)
- if self.x <= 0:
- self.moveRight()
-
- def move(self):
- self.health -= 1
- if self.direction == 1:
- self.moveUp()
- elif self.direction == 2:
- self.moveDown()
- elif self.direction == 3:
- self.moveRight()
- else:
- self.moveLeft()
-
- class Fish:
-
- x = random.randint(0,10)
- y = random.randint(0,10)
- direction = random.randint(1,4)
- def moveUp(self):
- y += 1
- if self.y >= 10:
- self.moveDown()
- def moveDown(self):
- y -= 1
- if self.y <= 0:
- self.moveUp(self)
- def moveRight(self):
- x += 1
- if self.x >= 10:
- self.moveLeft()
- def moveLeft(self):
- x -= 1
- if self.x <= 0:
- self.moveRight()
- def move(self):
- if self.direction == 1:
- self.moveUp()
- elif self.direction == 2:
- self.moveDown()
- elif self.direction == 3:
- self.moveRight()
- else:
- self.moveLeft()
- turtle = Turtle()
- fish = []
- for each_fish in range(10):
- afish = Fish()
- fish.append(afish)
- while 1:
- turtle.move()
- print('乌龟坐标是:%d,%d,体力是%d' % (turtle.x,turtle.y,turtle.health))
- for each in range(len(fish)):
- fish[each].move
- print('鱼%d的坐标是:%d,%d' %d (each,fish[each].x,fish[each].y))
- if turtle.x == fish[each].x and turtle.y == fish[each].y:
- turtle.health += 20
- print('鱼%d被吃了,乌龟的体力+20点,现在为%d点' % (each,turtle.health))
- fish.remove(fish[each])
- if fish == [] or turtle.health == 0:
- break
- print('游戏结束')
复制代码 |
|