超级玛丽碰砖块

turtle mario jump collision bricks 玛丽的算术之角色类

turtle mario jump collision bricks 玛丽的算术之角色类


操作超级玛丽去碰砖块的一个小游戏。这是一个雏形程序,方便学习。以下是代码预览。

"""
   超级玛丽碰砖块
   本程序定义一个Sprite类。
   操作它能跳跃起来,能左右移动去碰砖块。
"""
from turtle import *
from brick import Brick

class Sprite(Turtle):
    """
      继承自Turtle类的角色类
    """
    def __init__(self,leftpics,rightpics,pos):
        """初始化方法
           leftpics:左序列造型
           rightpics:右序列造型
           pos:初始坐标
        """
        Turtle.__init__(self,visible=False)
        self.penup()
        self.speed(0)
        self.leftpics = leftpics
        self.rightpics = rightpics
        self.images = [leftpics,rightpics]       
        self.shape_index = 0              # 造型序列索引号
        self.shape_amount = len(leftpics) # 向左或向右造型数量
        self.screen.onkeypress(self.leftmove,"Left")
        self.screen.onkeypress(self.rightmove,"Right")
        self.screen.listen()
        self.goto(pos)
        self.shape(self.images[0][0])     # 初始造型
        self.st()
        self.screen.update()
        self.dy = 0                       # 垂直速度
        self.gravity()
        self.screen.onkeypress(self.jump,"Up")
        
    def gravity(self):
        """受重力自由落体运动"""
        y = self.ycor() + self.dy        
        if y > -105:
           self.dy = self.dy -1
        else:
           y = -105
           self.dy = 0
        self.sety(y)
        self.screen.update()
        self.screen.ontimer(self.gravity,10)

    def jump(self):
        """跳跃"""
        if self.dy == 0 : self.dy = 20
        
    def leftmove(self):
        """向左移动"""
        self.setheading(180)       
        self.shape_index +=1                  # 造型索引增1 
        self.shape_index %= self.shape_amount # 对总数求余
        self.shape(self.images[0][self.shape_index])
        self.fd(10)
        self.screen.update()
        
    def rightmove(self):
        """向右移动"""
        self.setheading(0)        
        self.shape_index +=1                  # 造型索引增1 
        self.shape_index %= self.shape_amount # 对总数求余
        self.shape(self.images[1][self.shape_index])
        self.fd(10)
        self.screen.update()

下载完整源代码与素材,请

成为会员后,登陆才能继续浏览!联系微信scratch8即可办理会员。
(会员专属:能浏览所有文章,下载所有带链接的Python资源。)

关于李兴球

李兴球的博客是Python创意编程原创博客
此条目发表在python, turtle分类目录。将固定链接加入收藏夹。