tkinter超级玛丽颜色碰撞测试程序

tkinter超级玛丽颜色碰撞测试程序

python超级玛丽闯关gameturtle模块tkinter颜色碰撞检测试程序

"""
   超级玛丽颜色碰撞检测试程序.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]

bg_pics = [f'bgs/背景{i}.png' for i in range(1,4)]
bg_pics = [Image.open(im) for im in bg_pics]

# 生成背景
bg = GameTurtle(cv,bg_pics)
# 生成玛丽奥
mario = GameTurtle(cv,mario_pics,pos=(40,40))
mario.dy = 0

up_key = Key(cv,"Up")
down_key = Key(cv,"Down")
right_key = Key(cv,"Right")
left_key = Key(cv,"Left")

cv.focus_force()
cleftright=''               # 描述碰左或碰右或没有碰的变量
while True:
    mario.addy(mario.dy)
    if not mario.collide_color((0,255,82)):
        mario.dy += 0.1
    else:
        mario.dy = 0        
        if up_key.isdown():mario.dy=-5
    if not mario.collide_color((153,89,0)):cleftright=''
    
    if right_key.isdown():
        if cleftright=='left' or cleftright=='':
            mario.addx(2)
            if mario.collide_color((153,89,0)):
                cleftright='right'
            
    if left_key.isdown():
        if cleftright=='right'or cleftright=='':
            mario.addx(-2)               
            if mario.collide_color((153,89,0)):
                cleftright='left'
    
    root.title(cleftright + str(left_key.isdown()) + str(right_key.isdown()))
    if mario.xcor()>480:
        mario.setx(0)
        mario.sety(100)
        bg.nextshape()
    cv.update()
    time.sleep(0.01)

李兴球

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