python,练习乌龟吃鱼

'''
1.首先要有一个画布
2.随机乌龟和鱼的位置
3.移动
'''
import random as r 
list_x = [0,10]
list_y = [0,10]
class Turtle:    
    def __init__(self):
        #初始体力
        self.power=100
        #初始位置
        self.x = r.randint(list_x[0],list_x[1]) # 这里重点知道 randint
        self.y = r.randint(list_y[0],list_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<list_x[0]:
            self.x = list_x[0]-(new_x-list_x[0])
        elif new_x>list_x[1]:
            self.x = list_x[1]-(new_x-list_x[1])
        else:
            self.x = new_x
        #检查是否超出Y轴
        if new_y<list_y[0]:
            self.y = list_y[0]-(new_y-list_y[0])
        elif new_y>list_y[1]:
            self.y = list_y[1]-(new_y-list_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(list_x[0],list_x[1])
        self.y = r.randint(list_y[0],list_y[1])

    def move(self):
        # 随机移动位置
        new_x = self.x+r.choice([1,-1])
        new_y = self.y+r.choice([1,-1])
        #检查移动后是否超出区域
        if new_x<list_x[0]:
            self.x = list_x[0]-(new_x-list_x[0])
        elif new_x>list_x[1]:
            self.x = list_x[1]-(new_x-list_x[1])
        else:
            self.x = new_x
        #检查是否超出Y轴
        if new_y<list_y[0]:
            self.y = list_y[0]-(new_y-list_y[0])
        elif new_y>list_y[1]:
            self.y = list_y[1]-(new_y-list_y[1])
        else:
            self.y = new_y
        #返回移动后的位置 
        return (self.x,self.y)

t = Turtle()
fish = []
for i in range(10):
    new_fish = Fish()
    fish.append(new_fish)

while True:
    if not len(fish):
        print("鱼儿被吃完了,游戏结束")
        break
    if not t.power:
        print("乌龟体力耗尽,牺牲了")
        break
    pos = t.move()
    for each_fish in fish[:]:
        if each_fish.move() ==pos:
            #鱼儿被吃掉
            t.eat()
            fish.remove(each_fish)
            print("有一条鱼被吃了")

 

转载于:https://www.cnblogs.com/pengpengzhang/p/8711359.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值