栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

【Python游戏】Python各大游戏合集:超级玛丽、天天酷跑、我的世界、魔塔、雷霆战机 | 附带源码

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Python游戏】Python各大游戏合集:超级玛丽、天天酷跑、我的世界、魔塔、雷霆战机 | 附带源码

相关文件

关注小编,私信小编领取哟!
当然别忘了一件三连哟~~

公众号:Python日志
可以关注小编公众号,会不定时的发布一下Python小技巧,还有很多资源可以免费领取哟!!
源码领取:加Python学习交流群:773162165 可以领取哟

开发工具

Python版本:3.7.8
相关模块:
pytorch模块;
pyqt5模块;
numpy模块;
pyttsx3模块;
以及一些python自带的模块。

环境搭建

安装Python并添加到环境变量,pip安装需要的相关模块即可。

一:超级玛丽

效果展示


部分源码

class Box(pg.sprite.Sprite):
    def __init__(self, x, y, type, group=None, name=c.MAP_BOX):
        pg.sprite.Sprite.__init__(self)
        
        self.frames = []
        self.frame_index = 0
        self.load_frames()
        self.image = self.frames[self.frame_index]
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

        self.rest_height = y
        self.animation_timer = 0
        self.first_half = True   # First half of animation cycle
        self.state = c.RESTING
        self.y_vel = 0
        self.gravity = 1.2
        self.type = type
        self.group = group
        self.name = name
        
    def load_frames(self):
        sheet = setup.GFX['tile_set']
        frame_rect_list = [(384, 0, 16, 16), (400, 0, 16, 16), 
            (416, 0, 16, 16), (400, 0, 16, 16), (432, 0, 16, 16)]
        for frame_rect in frame_rect_list:
            self.frames.append(tools.get_image(sheet, *frame_rect, 
                            c.BLACK, c.BRICK_SIZE_MULTIPLIER))
    
    def update(self, game_info):
        self.current_time = game_info[c.CURRENT_TIME]
        if self.state == c.RESTING:
            self.resting()
        elif self.state == c.BUMPED:
            self.bumped()

    def resting(self):
        time_list = [375, 125, 125, 125]
        if (self.current_time - self.animation_timer) > time_list[self.frame_index]:
            self.frame_index += 1
            if self.frame_index == 4:
                self.frame_index = 0
            self.animation_timer = self.current_time

        self.image = self.frames[self.frame_index]
    
    def bumped(self):
        self.rect.y += self.y_vel
        self.y_vel += self.gravity
        
        if self.rect.y > self.rest_height + 5:
            self.rect.y = self.rest_height
            self.state = c.OPENED
            if self.type == c.TYPE_MUSHROOM:
                self.group.add(powerup.Mushroom(self.rect.centerx, self.rect.y))
            elif self.type == c.TYPE_FIREFLOWER:
                self.group.add(powerup.FireFlower(self.rect.centerx, self.rect.y))
            elif self.type == c.TYPE_LIFEMUSHROOM:
                self.group.add(powerup.LifeMushroom(self.rect.centerx, self.rect.y))
        self.frame_index = 4
        self.image = self.frames[self.frame_index]
    
    def start_bump(self, score_group):
        self.y_vel = -6
        self.state = c.BUMPED
        
        if self.type == c.TYPE_COIN:
            self.group.add(coin.Coin(self.rect.centerx, self.rect.y, score_group))
class Coin(pg.sprite.Sprite):
    def __init__(self, x, y, score_group):
        pg.sprite.Sprite.__init__(self)
        
        self.frames = []
        self.frame_index = 0
        self.load_frames()
        self.image = self.frames[self.frame_index]
        self.rect = self.image.get_rect()
        self.rect.centerx = x
        self.rect.bottom = y - 5
        self.gravity = 1
        self.y_vel = -15
        self.animation_timer = 0
        self.initial_height = self.rect.bottom - 5
        self.score_group = score_group
        
    def load_frames(self):
        sheet = setup.GFX[c.ITEM_SHEET]
        frame_rect_list = [(52, 113, 8, 14), (4, 113, 8, 14), 
                        (20, 113, 8, 14), (36, 113, 8, 14)]
        for frame_rect in frame_rect_list:
            self.frames.append(tools.get_image(sheet, *frame_rect, 
                            c.BLACK, c.BRICK_SIZE_MULTIPLIER))
    
    def update(self, game_info):
        self.current_time = game_info[c.CURRENT_TIME]
        self.spinning()
    
    def spinning(self):
        self.image = self.frames[self.frame_index]
        self.rect.y += self.y_vel
        self.y_vel += self.gravity
        
        if (self.current_time - self.animation_timer) > 80:
            if self.frame_index < 3:
                self.frame_index += 1
            else:
                self.frame_index = 0
            self.animation_timer = self.current_time
        
        if self.rect.bottom > self.initial_height:
            self.kill()
            
class FlashCoin(pg.sprite.Sprite):
    def __init__(self, x, y):
        pg.sprite.Sprite.__init__(self)
        self.frame_index = 0
        self.frames = []
        self.load_frames()
        self.image = self.frames[self.frame_index]
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.animation_timer = 0
        
    def load_frames(self):
        sheet = setup.GFX[c.ITEM_SHEET]
        frame_rect_list = [(1, 160, 5, 8), (9, 160, 5, 8),
                        (17, 160, 5, 8), (9, 160, 5, 8)]
        for frame_rect in frame_rect_list:
            self.frames.append(tools.get_image(sheet, *frame_rect, 
                            c.BLACK, c.BRICK_SIZE_MULTIPLIER))

    def update(self, current_time):
        time_list = [375, 125, 125, 125]
        if self.animation_timer == 0:
            self.animation_timer = current_time
        elif (current_time - self.animation_timer) > time_list[self.frame_index]:
            self.frame_index += 1
            if self.frame_index == 4:
                self.frame_index = 0
            self.animation_timer = current_time
        
        self.image = self.frames[self.frame_index]

class StaticCoin(pg.sprite.Sprite):
    def __init__(self, x, y):
        pg.sprite.Sprite.__init__(self)
        self.frame_index = 0
        self.frames = []
        self.load_frames()
        self.image = self.frames[self.frame_index]
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.animation_timer = 0

    def load_frames(self):
        sheet = setup.GFX[c.ITEM_SHEET]
        frame_rect_list = [(3, 98, 9, 13), (19, 98, 9, 13),
                        (35, 98, 9, 13), (51, 98, 9, 13)]
        for frame_rect in frame_rect_list:
            self.frames.append(tools.get_image(sheet, *frame_rect, 
                            c.BLACK, c.BRICK_SIZE_MULTIPLIER))

    def update(self, game_info):
        self.current_time = game_info[c.CURRENT_TIME]

        time_list = [375, 125, 125, 125]
        if self.animation_timer == 0:
            self.animation_timer = self.current_time
        elif (self.current_time - self.animation_timer) > time_list[self.frame_index]:
            self.frame_index += 1
            if self.frame_index == 4:
                self.frame_index = 0
            self.animation_timer = self.current_time
        
        self.image = self.frames[self.frame_index]
二:天天酷跑

效果展示


部分源码

class Role: #人物
    def __init__(self,surface=None,y=None):
        self.surface=surface
        self.y=y
        self.w=(surface.get_width())/12
        self.h=surface.get_height()/2
        self.currentFrame=-1
        self.state=0        #0代表跑步状态,1代表跳跃状态,2代表连续跳跃
        self.g=1            #重力加速度
        self.vy=0           #y轴速度       
        self.vy_start=-20   #起跳开始速度
    def getRect(self):
        return (0,self.y+12,self.w,self.h)


class Object:  #障碍物
    def __init__(self,surface,x=0,y=0):
        self.surface=surface
        self.x=x
        self.y=y
        self.w=surface.get_width()
        self.h=surface.get_height()
        self.currentFrame=random.randint(0,6)
        self.w = 100
        self.h = 100
    def getRect(self):
        return (self.x,self.y,self.w,self.h)
    def collision(self,rect1,rect2):
        #碰撞检测
        if (rect2[0]>=rect1[2]-20) or (rect1[0]+40>=rect2[2])or (rect1[1]+rect1[3]=508-85:
                role.y=508-85
                role.state=0
        #障碍物的移动
        addObject()
        
        for object in objectList:
            object.x-=10     #障碍物移动
            # 障碍物超出屏幕,移除障碍物
            if object.x+object.w<=0:
                objectList.remove(object)
                score+=10    #避开障碍物,加10分
                print("移除了一个目标")   
            #碰撞检测
            if object.collision(role.getRect(),object.getRect()):
                if(object.currentFrame==6):
                    objectList.remove(object)
                    score+=100  #吃金币加100分
                    print(score)
                    print("吃了一个金币")
                else: 
                    gameState=1   #游戏失败
                    print("发生了碰撞!")
三:我的世界

效果展示

部分代码展示

class Model(object):

    def __init__(self):

        # A Batch is a collection of vertex lists for batched rendering.
        self.batch = pyglet.graphics.Batch()

        # A TextureGroup manages an OpenGL texture.
        self.group = TextureGroup(image.load(TEXTURE_PATH).get_texture())

        # A mapping from position to the texture of the block at that position.
        # This defines all the blocks that are currently in the world.
        self.world = {}

        # Same mapping as `world` but only contains blocks that are shown.
        self.shown = {}

        # Mapping from position to a pyglet `VertextList` for all shown blocks.
        self._shown = {}

        # Mapping from sector to a list of positions inside that sector.
        self.sectors = {}

        # Simple function queue implementation. The queue is populated with
        # _show_block() and _hide_block() calls
        self.queue = deque()

        self._initialize()

    def _initialize(self):
        """ Initialize the world by placing all the blocks.

        """
        n = 80  # 1/2 width and height of world
        s = 1  # step size
        y = 0  # initial y height
        for x in xrange(-n, n + 1, s):
            for z in xrange(-n, n + 1, s):
                # create a layer stone an grass everywhere.
                self.add_block((x, y - 2, z), GRASS, immediate=False)
                self.add_block((x, y - 3, z), STONE, immediate=False)
                if x in (-n, n) or z in (-n, n):
                    # create outer walls.
                    for dy in xrange(-2, 3):
                        self.add_block((x, y + dy, z), STONE, immediate=False)

        # generate the hills randomly
        o = n - 10
        for _ in xrange(120):
            a = random.randint(-o, o)  # x position of the hill
            b = random.randint(-o, o)  # z position of the hill
            c = -1  # base of the hill
            h = random.randint(1, 6)  # height of the hill
            s = random.randint(4, 8)  # 2 * s is the side length of the hill
            d = 1  # how quickly to taper off the hills
            t = random.choice([GRASS, SAND, BRICK])
            for y in xrange(c, c + h):
                for x in xrange(a - s, a + s + 1):
                    for z in xrange(b - s, b + s + 1):
                        if (x - a) ** 2 + (z - b) ** 2 > (s + 1) ** 2:
                            continue
                        if (x - 0) ** 2 + (z - 0) ** 2 < 5 ** 2:
                            continue
                        self.add_block((x, y, z), t, immediate=False)
                s -= d  # decrement side length so hills taper off

    def hit_test(self, position, vector, max_distance=8):
        """ Line of sight search from current position. If a block is
        intersected it is returned, along with the block previously in the line
        of sight. If no block is found, return None, None.

        Parameters
        ----------
        position : tuple of len 3
            The (x, y, z) position to check visibility from.
        vector : tuple of len 3
            The line of sight vector.
        max_distance : int
            How many blocks away to search for a hit.

        """
        m = 8
        x, y, z = position
        dx, dy, dz = vector
        previous = None
        for _ in xrange(max_distance * m):
            key = normalize((x, y, z))
            if key != previous and key in self.world:
                return key, previous
            previous = key
            x, y, z = x + dx / m, y + dy / m, z + dz / m
        return None, None

    def exposed(self, position):
        """ Returns False is given `position` is surrounded on all 6 sides by
        blocks, True otherwise.

        """
        x, y, z = position
        for dx, dy, dz in FACES:
            if (x + dx, y + dy, z + dz) not in self.world:
                return True
        return False

    def add_block(self, position, texture, immediate=True):
        """ Add a block with the given `texture` and `position` to the world.

        Parameters
        ----------
        position : tuple of len 3
            The (x, y, z) position of the block to add.
        texture : list of len 3
            The coordinates of the texture squares. Use `tex_coords()` to
            generate.
        immediate : bool
            Whether or not to draw the block immediately.

        """
        if position in self.world:
            self.remove_block(position, immediate)
        self.world[position] = texture
        self.sectors.setdefault(sectorize(position), []).append(position)
        if immediate:
            if self.exposed(position):
                self.show_block(position)
            self.check_neighbors(position)

    def remove_block(self, position, immediate=True):
        """ Remove the block at the given `position`.

        Parameters
        ----------
        position : tuple of len 3
            The (x, y, z) position of the block to remove.
        immediate : bool
            Whether or not to immediately remove block from canvas.

        """
        del self.world[position]
        self.sectors[sectorize(position)].remove(position)
        if immediate:
            if position in self.shown:
                self.hide_block(position)
            self.check_neighbors(position)
四:魔塔游戏

效果展示


部分代码展示

ef init_actions():
    # QUIT:
    def quit(e):
        global running
        running = False
        return True
    
    # 注册事件
    action_control.register_action('QUIT', pygame.QUIT, quit)
    action_control.register_action('BOOK', pygame.KEYUP, global_var.get_value('BOOK').action)
    action_control.register_action('STARTMENU', pygame.KEYUP, global_var.get_value('STARTMENU').action)
    action_control.register_action('BACKPACK', pygame.KEYUP, global_var.get_value('BACKPACK').action)
    action_control.register_action('SAVE', pygame.KEYUP, global_var.get_value('SAVE').action)
    action_control.register_action('LOAD', pygame.KEYUP, global_var.get_value('LOAD').action)
    action_control.register_action('FLY', pygame.KEYUP, global_var.get_value('FLY').action)
    action_control.register_action('HELP', pygame.KEYUP, global_var.get_value('HELP').action)
    action_control.register_action('Shop1', pygame.KEYUP, global_var.get_value('Shop1').action)
    action_control.register_action('Shop2', pygame.KEYUP, global_var.get_value('Shop2').action)
    action_control.register_action('TEXTBOX', pygame.KEYUP, global_var.get_value('TEXTBOX').action)
    action_control.register_action('CHOICEBOX', pygame.KEYUP, global_var.get_value('CHOICEBOX').action)
    action_control.register_action('SHOWDAMAGE', pygame.KEYUP, global_var.get_value('SHOWDAMAGE').action)
    action_control.register_action('STATUSBAR', pygame.KEYUP, global_var.get_value('STATUSBAR').action)
    action_control.register_action('CURTAIN', pygame.KEYUP, global_var.get_value('CURTAIN').action)
    WriteLog.info(__name__, "事件全部注册完成")


def init_sound():
    Music = music.MusicWrapper()
    global_var.set_value("Music", Music)
    WriteLog.info(__name__, "初始化音效完成")

def init_event_flow():
    EVENTFLOW = EventFlow()
    global_var.set_value("EVENTFLOW", EVENTFLOW)
    EVENT = Event()
    global_var.set_value("EVENT", EVENT)
    EVENT.get_event_flow_module()
    EVENTFLOW.get_event_module()
    WriteLog.info(__name__, "初始化事件流完成")

def init_function():
    FUNCTION = global_var.get_value("FUNCTION")
    FUNCTION.init_var()
    WriteLog.info(__name__, "初始化function完成")

# DEBUG(开关在sysconf.py,如果开启将会启动控制台)
if DEBUG:
    import threading


    def console():
        while running:
            r = input()
            try:
                print(eval(r))
            except:
                try:
                    exec(r)
                except Exception as e:
                    print("error:", str(e))


    t = threading.Thread(target=console)
    t.start()

init()
init_actions()
init_sound()
init_event_flow()
init_function()
clock = pygame.time.Clock()

STARTMENU = global_var.get_value("STARTMENU")

# 主程序
while running:
    # a = pygame.time.get_ticks()
    # 展示开始菜单
    if STARTMENU.new_game == True:
        STARTMENU.open()
        STARTMENU.new_game = False
        # 默认开启显伤
        show_damage = global_var.get_value("SHOWDAMAGE")
        show_damage.open()
        # 默认开启状态栏
        status_bar = global_var.get_value("STATUSBAR")
        status_bar.open()
        # 地图确保为active状态
        CurrentMap.active = True
        # 载入初始事件
        EVENTFLOW = global_var.get_value("EVENTFLOW")
        with open(os.path.join(os.getcwd(),"project", "start_text.json")) as f:
            start_text = json.load(f)
        EVENTFLOW.insert_action(start_text["startText"])
    pygame.display.update()
    # 背景
    RootScreen.flush(screen)  # 显示刷新到屏幕
    action_control.action_render()  # 检查动作消息
    # b = pygame.time.get_ticks()
    # print(b - a)
五:雷霆战机

效果展示



部分代码展示

class Menu(object):
    """每个页面的父类"""

    def __init__(self, image, music):

        #设置背景音乐
        pygame.mixer.music.load(music)
        pygame.mixer.music.set_volume(0.4)
        pygame.mixer.music.play(-1)

        #设置屏幕大小
        self.screen = pygame.display.set_mode(SCREEN_RECT.size)
        #设置标题
        pygame.display.set_caption("雷霆战机 公众号:Python日志  学习交流群:685237705")
        #加载传入的图片并获取位置大小
        self.image = pygame.image.load(image)
        self.rect = self.image.get_rect()

    def event(self):
        #遍历所有事件
        for event in pygame.event.get():
            #点击游戏右上角的×关闭游戏
            if event.type == pygame.QUIT:
                pygame.quit()
                exit()
            #按下Esc键关闭游戏
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    exit()

        #获取鼠标是否点击和位置
        self.mouse_press = pygame.mouse.get_pressed()
        self.mouse_pos = pygame.mouse.get_pos()

    @staticmethod
    def clicks():
        #点击按钮时播放声音
        pygame.mixer.music.load("./music/mouse.mp3")
        #设置声音大小
        pygame.mixer.music.set_volume(0.5)
        #0为不循环播放,start为从音频的什么时候开始。
        pygame.mixer.music.play(loops=0, start=0.5)
        #500毫秒的时间慢慢退出
        pygame.mixer.music.fadeout(500)


class MainMenu(Menu):
    """游戏主菜单"""

    def __init__(self):
        #加载背景音乐和图片
        music = "./music/menu1.mp3"
        image = "./images/background2.png"
        super().__init__(image, music)

    def update_menu(self):

        while True:

            #调用父类的事件方法
            super().event()

            #加载按钮并获取位置
            start = pygame.image.load("./images/start1.png")
            start_rect = start.get_rect()
            rule = pygame.image.load("./images/rule1.png")
            rule_rect = rule.get_rect()

            # 开始键和查看键位置定位
            start_rect.centerx = SCREEN_RECT.centerx
            start_rect.y = SCREEN_RECT.height * 0.3
            rule_rect.centerx = SCREEN_RECT.centerx
            rule_rect.y = SCREEN_RECT.height * 0.45

            #判断鼠标的横纵坐标是否在按钮图片范围内
            if (start_rect.left < self.mouse_pos[0] < start_rect.right) and (
                            start_rect.top < self.mouse_pos[1] < start_rect.bottom):
                #在图片范围内则更换图片
                start = pygame.image.load("./images/start2.png")
                #按下鼠标左键,触发父类的私有方法发出鼠标声,并跳转页面
                if self.mouse_press[0]:
                    Menu.clicks()
                    GameType().update_menu()

            if (rule_rect.left < self.mouse_pos[0] < rule_rect.right) and (
                            rule_rect.top < self.mouse_pos[1] < rule_rect.bottom):
                rule = pygame.image.load("./images/rule2.png")
                if self.mouse_press[0]:
                    Menu.clicks()
                    RuleMenu().update_menu()

            #更新背景、开始按钮、规则按钮
            self.screen.blit(self.image, self.rect)
            self.screen.blit(start, start_rect)
            self.screen.blit(rule, rule_rect)
            pygame.display.update()


class GameType(Menu):
    """游戏模式选择"""

    def __init__(self):
        music = "./music/type1.mp3"
        image = "./images/background4.png"
        super().__init__(image, music)

    def update_menu(self):

        while True:

            super().event()

            type1 = pygame.image.load("./images/first1.png")
            type1_rect = type1.get_rect()
            type2 = pygame.image.load("./images/second1.png")
            type2_rect = type2.get_rect()
            type3 = pygame.image.load("./images/third1.png")
            type3_rect = type3.get_rect()
            return_picture = pygame.image.load("./images/return5.png")
            return_rect = return_picture.get_rect()

            type1_rect.centerx = SCREEN_RECT.centerx
            type1_rect.y = SCREEN_RECT.height * 0.15
            type2_rect.centerx = type1_rect.centerx
            type2_rect.y = SCREEN_RECT.height * 0.3
            type3_rect.centerx = SCREEN_RECT.centerx
            type3_rect.y = SCREEN_RECT.height * 0.45
            return_rect.x = 10
            return_rect.y = 10

            #调用自己的静态私有方法获取记录
            record1 = self.__record(str(1))
            record2 = self.__record(str(2))

            # 开始模式一
            if (type1_rect.left < self.mouse_pos[0] < type1_rect.right) and (
                            type1_rect.top < self.mouse_pos[1] < type1_rect.bottom):
                type1 = pygame.image.load("./images/first2.png")
                if self.mouse_press[0]:
                    Menu.clicks()
                    plane_main_1.Game().start_game()

            #开始模式二
            if (type2_rect.left < self.mouse_pos[0] < type2_rect.right) and (
                            type2_rect.top < self.mouse_pos[1] < type2_rect.bottom):
                type2 = pygame.image.load("./images/second2.png")
                if self.mouse_press[0]:
                    Menu.clicks()
                    #用获取的记录判断能否开启游戏关卡
                    if 0 <= int(record1) <= 3:
                        plane_main_2.Game().start_game()
                    else:
                        #不可以则调用禁止类的,显示禁止页面
                        ProhibitMenu().update_menu()

            #开始模式三
            if (type3_rect.left < self.mouse_pos[0] < type3_rect.right) and (
                            type3_rect.top < self.mouse_pos[1] < type3_rect.bottom):
                type3 = pygame.image.load("./images/third2.png")
                if self.mouse_press[0]:
                    Menu.clicks()
                    if 0 <= int(record2) <= 3:
                        plane_main_3.Game().start_game()
                    else:
                        ProhibitMenu().update_menu()

            if return_rect.left < self.mouse_pos[0] < return_rect.right and (
                            return_rect.top < self.mouse_pos[1] < return_rect.bottom):
                return_picture = pygame.image.load("./images/return6.png")
                if self.mouse_press[0]:
                    Menu.clicks()
                    MainMenu().update_menu()

            self.screen.blit(self.image, self.rect)
            self.screen.blit(type1, type1_rect)
            self.screen.blit(type2, type2_rect)
            self.screen.blit(type3, type3_rect)
            self.screen.blit(return_picture, return_rect)
            pygame.display.update()
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/869634.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号