"""
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)
def move(self):
"""朝自己的方向移动"""
self.fd(10)
def follow_mouse(event):
"""本函数让小海龟面朝鼠标指针移动"""
x = event.x - 240 # 转换成海龟坐标系中的x坐标
y = 180 - event.y # 转换成海龟坐标系中的y坐标
dy = y - blue_turtle.ycor()
dx = x - blue_turtle.xcor()
def shoot(x,y):
"""发射子弹"""
b = Bullet(x,y,blue_turtle.heading())
def born_turtle():
"""生成海龟对象"""
blue= Turtle(shape='turtle')
if __name__ =="__main__":
blue_turtle = born_turtle() # 生成海龟
bullets = [] # 子弹列表现
screen = Screen() # 新建屏幕对象
screen.bgcolor("gray") # 设置背景灰度
screen.setup(480,360) # 设置屏幕宽高
screen.delay(0) # 设置屏幕延时
screen.cv.bind("<Motion>",follow_mouse) # 绑定鼠标移动事件
screen.onclick(shoot) # 单击屏幕,发射子弹
screen.mainloop()
如需要查看完整代码,请
需要浏览更多吗?
成为会员后,登陆才能继续浏览!联系微信scratch8即可办理会员。
(会员专属:能浏览所有文章,下载所有带链接的Python资源。)

