【小甲鱼】Python课后作业 37课 类和对象(2)

测试题:

【小甲鱼】Python课后作业 37课 类和对象(2)_第1张图片
【小甲鱼】Python课后作业 37课 类和对象(2)_第2张图片
【小甲鱼】Python课后作业 37课 类和对象(2)_第3张图片
【小甲鱼】Python课后作业 37课 类和对象(2)_第4张图片

动动手:

37_0.py

【小甲鱼】Python课后作业 37课 类和对象(2)_第5张图片


class Ticket():

    def __init__(self,weekend = False,child = False):
        self.exp = 100
        if weekend :
            self.inc = 1.2
        else:
            self.inc = 1
        if child:
            self.discount = 0.5
        else:
            self.discount = 1

    def calcPrice(self,num):
        return self.exp * self.inc * self.discount * num

在这里插入图片描述

37_1.py

【小甲鱼】Python课后作业 37课 类和对象(2)_第6张图片

# 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])

        #检查是否超出x轴边界

        if new_x < legal_x[0]:
            self.x = legal_x[0] - (new_x - legal_x[0])
        elif new_x > legal_x[1]:
            self.x = legal_x[1] - (new_x - legal_x[1])

        else:
            self.x = new_x
        #检查是否超出y轴边界

        if new_y < legal_y[0]:
            self.y = legal_x[0] - (new_y - legal_y[0])
        elif new_y > legal_y[1]:
            self.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])
        #检查是否超出x轴边界

        if new_x < legal_x[0]:
            self.x = legal_x[0] - (new_x - legal_x[0])
        elif new_x > legal_x[1]:
            self.x = legal_x[1] - (new_x - legal_x[1])

        else:
            self.x = new_x
        #检查是否超出y轴边界

        if new_y < legal_y[0]:
            self.y = legal_x[0] - (new_y - legal_y[0])
        elif new_y > legal_y[1]:
            self.y = legal_y[1] - (new_y - legal_y[1])

        else:
            self.y = new_y


        return (self.x,self.y)


turtle = Turtle()
fish = []
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('有一条鱼儿被吃掉了...')
    

【小甲鱼】Python课后作业 37课 类和对象(2)_第7张图片

你可能感兴趣的:(编程语言)