• 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("有一条鱼被吃了")
  • 相关阅读:
    ycsb
    Tikv docker-compose go client
    Raft 协议
    kubectl 命令
    JAVA判断是否是微信内置浏览器,是否是在微信内打开
    IDEA设置默认maven配置
    JAVA中JDK1.8的LocalDateTime日期类的操作方法
    JAVA在JDK1.8中Stream流的使用
    Linux(Centos)部署Jenkins
    Linux(Centos)安装maven
  • 原文地址:https://www.cnblogs.com/pengpengzhang/p/8711359.html
Copyright © 2020-2023  润新知