
李兴球Python的游戏海龟gameturtle模块上下左右矩形碰撞检测
"""
超级玛丽上下左右矩形碰撞检测程序.py
本程序需要gameturtle模块0.2版支持。
"""
from gameturtle import *
class Key:
def __init__(self,cv,key):
self._canvas = cv
self._key = key
self._down = False
self._canvas.bind("" % key,self._press)
self._canvas.bind("" % key,self._release)
def _press(self,event):
self._down = True
def _release(self,event):
self._down = False
def isdown(self):
return self._down
root = Tk()
cv = Canvas(width=480,height=360)
cv.pack()
# 加载资源
mario_pics = ['bgs/mariox.png','bgs/mario2x.png']
mario_pics = [Image.open(im) for im in mario_pics]
# 生成玛丽奥
mario = GameTurtle(cv,mario_pics,pos=(40,40))
mario.dy = 0
square1 = GameTurtle(cv,Image.new("RGBA",(240,120),color='red'))
up_key = Key(cv,"Up")
down_key = Key(cv,"Down")
right_key = Key(cv,"Right")
left_key = Key(cv,"Left")
cv.focus_force()
while True:
if right_key.isdown() and not mario.right_collide(square1):mario.addx(2)
if left_key.isdown() and not mario.left_collide(square1):mario.addx(-2)
if up_key.isdown() and not mario.top_collide(square1):mario.addy(-2)
if down_key.isdown() and not mario.bottom_collide(square1):mario.addy(2)
if mario.left_collide(square1):root.title('左碰')
if mario.right_collide(square1):root.title('右碰')
if mario.top_collide(square1):root.title('上碰')
if mario.bottom_collide(square1):root.title('下碰')
cv.update()
time.sleep(0.01)