zoukankan      html  css  js  c++  java
  • 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("有一条鱼被吃了")
  • 相关阅读:
    my first android test
    VVVVVVVVVV
    my first android test
    my first android test
    my first android test
    ini文件
    ZZZZ
    Standard Exception Classes in Python 1.5
    Python Module of the Week Python Module of the Week
    my first android test
  • 原文地址:https://www.cnblogs.com/pengpengzhang/p/8711359.html
Copyright © 2011-2022 走看看