继承Turtle类的随机移动的地球

继承Turtle类的随机移动的地球

李兴球Python继承自Turtle类随机移动的地球

李兴球Python继承自Turtle类随机移动的地球

李兴球Python继承自Turtle类随机移动的地球


地球挣脱了太阳的束缚,发疯了,人类早就彻底灭亡了?以下是完整源代码。本程序面向有一定Python基础的人士阅读,至少要学过面向对象编程的继承。

"""
   继承自Turtle类的碰到边缘有会反弹随机移动的球.
"""
from turtle import *
from random import randint
from time import sleep

class Ranger(Turtle):
    def __init__(self,image,x,y):
        Turtle.__init__(self,shape = image,visible=False)
        self.penup()
        self.screen_width = self.screen.window_width()
        self.screen_height = self.screen.window_height()
        self.xspeed = randint(-10,10)
        self.yspeed = randint(-10,10)
        self.dead = False
        self.timecounter = 0              # 延迟计数器
        self.timeamount = 3               #  总共延迟时间
        self.goto(x,y)
        self.onclick(self.hide)
        self.setheading(randint(1,360))
        self.st()
        self.move()
        
    def move(self):
        if not self.dead:
            if randint(1,30) == 1 : self.set_random_heading()
            self.setx( self.xcor() + self.xspeed)
            self.sety( self.ycor() + self.yspeed)
            x = self.xcor()
            y =  self.ycor()       
            if abs(x) > self.screen_width//2 - 50:
                self.xspeed = - self.xspeed
                
            if abs(y) > self.screen_height//2 - 50:
                self.yspeed = - self.yspeed
            self.screen.ontimer(self.move,10)

    def hide(self,x,y):
        """隐藏自己"""       
        self.dead = True           
        
    def set_random_heading(self):
        """随机设定水平速度和垂直速度"""
        self.xspeed = randint(-10,10)
        self.yspeed = randint(-10,10)      
        

if __name__ == "__main__":

    screen = Screen()
    screen.bgpic('太空.png')
    screen.title(' 继承自Turtle类的碰到边缘有会反弹随机移动的球')
    screen.delay(0)
    image = "星球\\0.gif"
    screen.addshape(image)
    r = Ranger(image,0,100)
    screen.mainloop()
    
            
        

李兴球

李兴球的博客是Python创意编程原创博客