Python海龟画图用鼠标控制角色的射击游戏练习程序

Python海龟画图用鼠标控制角色的射击游戏练习程序

"""
Python海龟画图用鼠标控制角色的射击游戏练习程序。
本程序可以实时获取鼠标指针的x,y坐标,作者:李兴球
原理:通过获取screen的canvas,对<Motion>鼠标移动事件进行绑定.
由于turtle的坐标系的不同,所以要进行坐标转换.
"""
#从海龟模块导入所有命令

from turtle import *
import math

class Bullet(Turtle):
    def __init__(self,x,y,h):
        Turtle.__init__(self,visible=False,shape="circle")
        self.penup()
        self.dead = False
        self.goto(x,y)
        self.setheading(h)
        self.showturtle()
        self.move()
        
    def move(self):
        """朝自己的方向移动"""
        self.fd(10)
        if self.碰到边缘():self.dead = True
        if self.dead:
            self.hideturtle()
            del self
            #print("我自杀好吧")
        else:
            screen.ontimer(self.move,10)

    def 碰到边缘(self):
        return abs(self.xcor())>240 or abs(self.ycor())>180
        

def follow_mouse(event):
    """本函数让小海龟面朝鼠标指针移动"""
    x = event.x - 240              # 转换成海龟坐标系中的x坐标
    y = 180 - event.y              # 转换成海龟坐标系中的y坐标
    dy = y - blue_turtle.ycor()
    dx = x - blue_turtle.xcor()
    angle = math.degrees(math.atan2(dy,dx))
    blue_turtle.setheading(angle)
    if blue_turtle.distance(x,y)>50:blue_turtle.fd(10)
    s = "鼠标指针坐标:" + str(x) + "," + str(y) + "方向:" + str(int(angle))
    s = s + "  by lixingqiu"
    screen.title(s)

def shoot(x,y):
    """发射子弹"""
    b = Bullet(x,y,blue_turtle.heading())
    bullets.append(b)
    # 移去dead为True的子弹
    for b in bullets:
        if b.dead :bullets.remove(b)
 

You must log in to read the rest of this article. Please log in or register as a user.