基于Python实现超级玛丽游戏的示例代码

目录
  • 效果演示
  • 基础源码
    • 1.基础设置(tools部分)
    • 2.设置背景音乐以及场景中的文字(setup部分)
    • 3.设置游戏规则(load_screen)
    • 4.设置游戏内菜单等(main_menu)
    • 5.main()
    • 6.调用以上函数实现

效果演示

基础源码

1.基础设置(tools部分)

这个部分设置马里奥以及游戏中蘑菇等怪的的移动设置。

import os
import pygame as pg

keybinding = {
    'action':pg.K_s,
    'jump':pg.K_a,
    'left':pg.K_LEFT,
    'right':pg.K_RIGHT,
    'down':pg.K_DOWN
}

class Control(object):
    """Control class for entire project. Contains the game loop, and contains
    the event_loop which passes events to States as needed. Logic for flipping
    states is also found here."""
    def __init__(self, caption):
        self.screen = pg.display.get_surface()
        self.done = False
        self.clock = pg.time.Clock()
        self.caption = caption
        self.fps = 60
        self.show_fps = False
        self.current_time = 0.0
        self.keys = pg.key.get_pressed()
        self.state_dict = {}
        self.state_name = None
        self.state = None

    def setup_states(self, state_dict, start_state):
        self.state_dict = state_dict
        self.state_name = start_state
        self.state = self.state_dict[self.state_name]

    def update(self):
        self.current_time = pg.time.get_ticks()
        if self.state.quit:
            self.done = True
        elif self.state.done:
            self.flip_state()
        self.state.update(self.screen, self.keys, self.current_time)

    def flip_state(self):
        previous, self.state_name = self.state_name, self.state.next
        persist = self.state.cleanup()
        self.state = self.state_dict[self.state_name]
        self.state.startup(self.current_time, persist)
        self.state.previous = previous

    def event_loop(self):
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.done = True
            elif event.type == pg.KEYDOWN:
                self.keys = pg.key.get_pressed()
                self.toggle_show_fps(event.key)
            elif event.type == pg.KEYUP:
                self.keys = pg.key.get_pressed()
            self.state.get_event(event)

    def toggle_show_fps(self, key):
        if key == pg.K_F5:
            self.show_fps = not self.show_fps
            if not self.show_fps:
                pg.display.set_caption(self.caption)

    def main(self):
        """Main loop for entire program"""
        while not self.done:
            self.event_loop()
            self.update()
            pg.display.update()
            self.clock.tick(self.fps)
            if self.show_fps:
                fps = self.clock.get_fps()
                with_fps = "{} - {:.2f} FPS".format(self.caption, fps)
                pg.display.set_caption(with_fps)

class _State(object):
    def __init__(self):
        self.start_time = 0.0
        self.current_time = 0.0
        self.done = False
        self.quit = False
        self.next = None
        self.previous = None
        self.persist = {}

    def get_event(self, event):
        pass

    def startup(self, current_time, persistant):
        self.persist = persistant
        self.start_time = current_time

    def cleanup(self):
        self.done = False
        return self.persist

    def update(self, surface, keys, current_time):
        pass

def load_all_gfx(directory, colorkey=(255,0,255), accept=('.png', 'jpg', 'bmp')):
    graphics = {}
    for pic in os.listdir(directory):
        name, ext = os.path.splitext(pic)
        if ext.lower() in accept:
            img = pg.image.load(os.path.join(directory, pic))
            if img.get_alpha():
                img = img.convert_alpha()
            else:
                img = img.convert()
                img.set_colorkey(colorkey)
            graphics[name]=img
    return graphics

def load_all_music(directory, accept=('.wav', '.mp3', '.ogg', '.mdi')):
    songs = {}
    for song in os.listdir(directory):
        name,ext = os.path.splitext(song)
        if ext.lower() in accept:
            songs[name] = os.path.join(directory, song)
    return songs

def load_all_fonts(directory, accept=('.ttf')):
    return load_all_music(directory, accept)

def load_all_sfx(directory, accept=('.wav','.mpe','.ogg','.mdi')):
    effects = {}
    for fx in os.listdir(directory):
        name, ext = os.path.splitext(fx)
        if ext.lower() in accept:
            effects[name] = pg.mixer.Sound(os.path.join(directory, fx))
    return effects

2.设置背景音乐以及场景中的文字(setup部分)

该部分主要设置场景中的背景音乐,以及字体的显示等设置。

import os
import pygame as pg
from . import tools
from .import constants as c

ORIGINAL_CAPTION = c.ORIGINAL_CAPTION

os.environ['SDL_VIDEO_CENTERED'] = '1'
pg.init()
pg.event.set_allowed([pg.KEYDOWN, pg.KEYUP, pg.QUIT])
pg.display.set_caption(c.ORIGINAL_CAPTION)
SCREEN = pg.display.set_mode(c.SCREEN_SIZE)
SCREEN_RECT = SCREEN.get_rect()

FONTS = tools.load_all_fonts(os.path.join("resources","fonts"))
MUSIC = tools.load_all_music(os.path.join("resources","music"))
GFX   = tools.load_all_gfx(os.path.join("resources","graphics"))
SFX   = tools.load_all_sfx(os.path.join("resources","sound"))

3.设置游戏规则(load_screen)

from .. import setup, tools
from .. import constants as c
from .. import game_sound
from ..components import info

class LoadScreen(tools._State):
    def __init__(self):
        tools._State.__init__(self)

    def startup(self, current_time, persist):
        self.start_time = current_time
        self.persist = persist
        self.game_info = self.persist
        self.next = self.set_next_state()

        info_state = self.set_overhead_info_state()

        self.overhead_info = info.OverheadInfo(self.game_info, info_state)
        self.sound_manager = game_sound.Sound(self.overhead_info)

    def set_next_state(self):
        """Sets the next state"""
        return c.LEVEL1

    def set_overhead_info_state(self):
        """sets the state to send to the overhead info object"""
        return c.LOAD_SCREEN

    def update(self, surface, keys, current_time):
        """Updates the loading screen"""
        if (current_time - self.start_time) < 2400:
            surface.fill(c.BLACK)
            self.overhead_info.update(self.game_info)
            self.overhead_info.draw(surface)

        elif (current_time - self.start_time) < 2600:
            surface.fill(c.BLACK)

        elif (current_time - self.start_time) < 2635:
            surface.fill((106, 150, 252))

        else:
            self.done = True

class GameOver(LoadScreen):
    """A loading screen with Game Over"""
    def __init__(self):
        super(GameOver, self).__init__()

    def set_next_state(self):
        """Sets next state"""
        return c.MAIN_MENU

    def set_overhead_info_state(self):
        """sets the state to send to the overhead info object"""
        return c.GAME_OVER

    def update(self, surface, keys, current_time):
        self.current_time = current_time
        self.sound_manager.update(self.persist, None)

        if (self.current_time - self.start_time) < 7000:
            surface.fill(c.BLACK)
            self.overhead_info.update(self.game_info)
            self.overhead_info.draw(surface)
        elif (self.current_time - self.start_time) < 7200:
            surface.fill(c.BLACK)
        elif (self.current_time - self.start_time) < 7235:
            surface.fill((106, 150, 252))
        else:
            self.done = True

class TimeOut(LoadScreen):
    """Loading Screen with Time Out"""
    def __init__(self):
        super(TimeOut, self).__init__()

    def set_next_state(self):
        """Sets next state"""
        if self.persist[c.LIVES] == 0:
            return c.GAME_OVER
        else:
            return c.LOAD_SCREEN

    def set_overhead_info_state(self):
        """Sets the state to send to the overhead info object"""
        return c.TIME_OUT

    def update(self, surface, keys, current_time):
        self.current_time = current_time

        if (self.current_time - self.start_time) < 2400:
            surface.fill(c.BLACK)
            self.overhead_info.update(self.game_info)
            self.overhead_info.draw(surface)
        else:
            self.done = True

4.设置游戏内菜单等(main_menu)

import pygame as pg
from .. import setup, tools
from .. import constants as c
from .. components import info, mario

class Menu(tools._State):
    def __init__(self):
        """Initializes the state"""
        tools._State.__init__(self)
        persist = {c.COIN_TOTAL: 0,
                   c.SCORE: 0,
                   c.LIVES: 3,
                   c.TOP_SCORE: 0,
                   c.CURRENT_TIME: 0.0,
                   c.LEVEL_STATE: None,
                   c.CAMERA_START_X: 0,
                   c.MARIO_DEAD: False}
        self.startup(0.0, persist)

    def startup(self, current_time, persist):
        """Called every time the game's state becomes this one.  Initializes
        certain values"""
        self.next = c.LOAD_SCREEN
        self.persist = persist
        self.game_info = persist
        self.overhead_info = info.OverheadInfo(self.game_info, c.MAIN_MENU)

        self.sprite_sheet = setup.GFX['title_screen']
        self.setup_background()
        self.setup_mario()
        self.setup_cursor()

    def setup_cursor(self):
        """Creates the mushroom cursor to select 1 or 2 player game"""
        self.cursor = pg.sprite.Sprite()
        dest = (220, 358)
        self.cursor.image, self.cursor.rect = self.get_image(
            24, 160, 8, 8, dest, setup.GFX['item_objects'])
        self.cursor.state = c.PLAYER1

    def setup_mario(self):
        """Places Mario at the beginning of the level"""
        self.mario = mario.Mario()
        self.mario.rect.x = 110
        self.mario.rect.bottom = c.GROUND_HEIGHT

    def setup_background(self):
        """Setup the background image to blit"""
        self.background = setup.GFX['level_1']
        self.background_rect = self.background.get_rect()
        self.background = pg.transform.scale(self.background,
                                   (int(self.background_rect.width*c.BACKGROUND_MULTIPLER),
                                    int(self.background_rect.height*c.BACKGROUND_MULTIPLER)))
        self.viewport = setup.SCREEN.get_rect(bottom=setup.SCREEN_RECT.bottom)

        self.image_dict = {}
        self.image_dict['GAME_NAME_BOX'] = self.get_image(
            1, 60, 176, 88, (170, 100), setup.GFX['title_screen'])

    def get_image(self, x, y, width, height, dest, sprite_sheet):
        """Returns images and rects to blit onto the screen"""
        image = pg.Surface([width, height])
        rect = image.get_rect()

        image.blit(sprite_sheet, (0, 0), (x, y, width, height))
        if sprite_sheet == setup.GFX['title_screen']:
            image.set_colorkey((255, 0, 220))
            image = pg.transform.scale(image,
                                   (int(rect.width*c.SIZE_MULTIPLIER),
                                    int(rect.height*c.SIZE_MULTIPLIER)))
        else:
            image.set_colorkey(c.BLACK)
            image = pg.transform.scale(image,
                                   (int(rect.width*3),
                                    int(rect.height*3)))

        rect = image.get_rect()
        rect.x = dest[0]
        rect.y = dest[1]
        return (image, rect)

    def update(self, surface, keys, current_time):
        """Updates the state every refresh"""
        self.current_time = current_time
        self.game_info[c.CURRENT_TIME] = self.current_time
        self.update_cursor(keys)
        self.overhead_info.update(self.game_info)

        surface.blit(self.background, self.viewport, self.viewport)
        surface.blit(self.image_dict['GAME_NAME_BOX'][0],
                     self.image_dict['GAME_NAME_BOX'][1])
        surface.blit(self.mario.image, self.mario.rect)
        surface.blit(self.cursor.image, self.cursor.rect)
        self.overhead_info.draw(surface)

    def update_cursor(self, keys):
        """Update the position of the cursor"""
        input_list = [pg.K_RETURN, pg.K_a, pg.K_s]

        if self.cursor.state == c.PLAYER1:
            self.cursor.rect.y = 358
            if keys[pg.K_DOWN]:
                self.cursor.state = c.PLAYER2
            for input in input_list:
                if keys[input]:
                    self.reset_game_info()
                    self.done = True
        elif self.cursor.state == c.PLAYER2:
            self.cursor.rect.y = 403
            if keys[pg.K_UP]:
                self.cursor.state = c.PLAYER1

    def reset_game_info(self):
        """Resets the game info in case of a Game Over and restart"""
        self.game_info[c.COIN_TOTAL] = 0
        self.game_info[c.SCORE] = 0
        self.game_info[c.LIVES] = 3
        self.game_info[c.CURRENT_TIME] = 0.0
        self.game_info[c.LEVEL_STATE] = None

        self.persist = self.game_info

5.main()

from . import setup,tools
from .states import main_menu,load_screen,level1
from . import constants as c

def main():
    """Add states to control here."""
    run_it = tools.Control(setup.ORIGINAL_CAPTION)
    state_dict = {c.MAIN_MENU: main_menu.Menu(),
                  c.LOAD_SCREEN: load_screen.LoadScreen(),
                  c.TIME_OUT: load_screen.TimeOut(),
                  c.GAME_OVER: load_screen.GameOver(),
                  c.LEVEL1: level1.Level1()}

    run_it.setup_states(state_dict, c.MAIN_MENU)
    run_it.main()

6.调用以上函数实现

import sys
import pygame as pg
from 小游戏.超级玛丽.data.main import main
import cProfile

if __name__=='__main__':
    main()
    pg.quit()
    sys.exit()

以上就是基于Python实现超级玛丽游戏的示例代码的详细内容,更多关于Python超级玛丽的资料请关注我们其它相关文章!

(0)

相关推荐

  • python 实现超级玛丽游戏

    开发需求 python 3.7+ pygame 1.9+ 演示 项目地址 https://github.com/Mr-han11/PythonSuperMario-master 主要功能的代码实现 玩家 __author__ = 'marble_xu' import os import json import pygame as pg from .. import setup, tools from .. import constants as c from ..components impor

  • python实现超级玛丽游戏

    python制作超级玛丽游戏,供大家参考,具体内容如下 这篇文章,我们优先介绍超级玛丽游戏中的多状态跳跃,和行走地图拖动的原理,然后实现.并实现倒计时和金币动态效果 接下来用下面这四张图,就可以完全懂得游戏中背景是怎么会移动的. 图1 图2 图3 图4 由于代码是我前几年学习python的时候做的,代码写的很挤都整到一个源文件中,大家看的时候仔细. 然后上源代码: #!/usr/bin/env python # -*- coding:utf-8 -*- import pygame,os,wx f

  • python游戏实战项目之童年经典超级玛丽

    导语 "超级玛丽"--有多少人还记得这款经典游戏?那个戴帽子的大胡子穿着背带裤的马里奥! 带您重温经典的回忆,超级马里奥拯救不开心!炫酷来袭. 如果您的童年,也曾被魔性的 灯~灯灯~灯~灯灯~灯洗脑~那就来怀旧一番吧! 我是华丽的分割线------------------------------ 往期写过游戏实战已经积累到30几篇了哦~嘿嘿,推一波之前的,狗头保命.jpg. 欢迎大家来领免费的游戏,开玩啦~源码可以直接找我拿滴! 在座的各位大佬,你们都玩过这里面的几个游戏吖? ​ 往期

  • 基于Python实现超级玛丽游戏的示例代码

    目录 效果演示 基础源码 1.基础设置(tools部分) 2.设置背景音乐以及场景中的文字(setup部分) 3.设置游戏规则(load_screen) 4.设置游戏内菜单等(main_menu) 5.main() 6.调用以上函数实现 效果演示 基础源码 1.基础设置(tools部分) 这个部分设置马里奥以及游戏中蘑菇等怪的的移动设置. import os import pygame as pg keybinding = { 'action':pg.K_s, 'jump':pg.K_a, 'l

  • 基于Python实现围棋游戏的示例代码

    目录 1.导入模块 2.初始化棋盘 3. 开始游戏 4.放弃当前回合落子 5.悔棋判断 6.重新开始 7.右侧太极图的设置 8.落子设置 9.吃子规则判定设置 10.其他 11.程序入口 12.效果图 文件自取 1.导入模块 tkinter:ttk覆盖tkinter部分对象,ttk对tkinter进行了优化 copy:深拷贝时需要用到copy模块 tkinter.messagebox:围棋应用对象定义 如没有以上模块,在pycharm终端输入以下指令: pip install 相应模块 -i h

  • Python实现生命游戏的示例代码(tkinter版)

    目录 生命游戏(Game of Life) 游戏概述 生存定律 图形结构 代码实现 运行界面 使用简介 后续改进 生命游戏(Game of Life) 由剑桥大学约翰·何顿·康威设计的计算机程序.美国趣味数学大师马丁·加德纳(Martin Gardner,1914-2010)通过<科学美国人>杂志,将康威的生命游戏介绍给学术界之外的广大渎者,一时吸引了各行各业一大批人的兴趣,这时细胞自动机课题才吸引了科学家的注意. 游戏概述 用一个二维表格表示“生存空间”,空间的每个方格中都可放置一个生命细胞

  • python实现生命游戏的示例代码(Game of Life)

    生命游戏的算法就不多解释了,百度一下介绍随处可见. 因为网上大多数版本都是基于pygame,matlab等外部库实现的,二维数组大多是用numpy,使用起来学习成本比较高,所以闲暇之余写一个不用外部依赖库,console输出的版本. # -*- coding: utf-8 -*- from time import sleep from copy import deepcopy WORLD_HIGH = 20 #世界长度 WORLD_WIDE = 40 #世界宽度 ALIVE_CON = 3 #复

  • python 实现弹球游戏的示例代码

    运行效果 实现代码 # -*- coding: utf-8 -*- import tkinter as tkinter import tkinter.messagebox as mb import random,time class Ball(): ''' 创建Ball类,初始化对象,即创建对象设置属性, init函数是在对象被创建的同时就设置属性的一种方法,Python会在创建新对象时自动调用这个函数. ''' def __init__(self,canvas,paddle,score,col

  • 快速实现基于Python的微信聊天机器人示例代码

    最近听说一个很好玩的图灵机器人api,正好可以用它做一个微信聊天机器人,下面是实现 # test.py import requests import itchat #这是一个用于微信回复的库 KEY = '8edce3ce905a4c1dbb965e6b35c3834d' #这个key可以直接拿来用 # 向api发送请求 def get_response(msg): apiUrl = 'http://www.tuling123.com/openapi/api' data = { 'key' :

  • 基于Python编写简易版的天天跑酷游戏的示例代码

    写出来的效果图就是这样了: 下面就更新一下全部的代码吧 还是老样子先定义 import pygame,sys import random 写一下游戏配置 width = 1200            #窗口宽度 height = 508            #窗口高度 size = width, height    score=None              #分数 myFont=myFont1=None     #字体 surObject=None          #障碍物图片   

  • 基于Python实现开心消消乐小游戏的示例代码

    目录 前言 一.准备 1.1 图片素材 1.2 音频素材 二.代码 2.1 导入模块 2.2 游戏音乐设置 2.3 制作树类 2.4 制作鼠标点击效果 2.5 制作出现元素 2.6 数组 2.7 制作人物画板 三.效果展示(仅部分) 3.1 初始页面 3.2 第一关画面 3.3 失败画面 3.4 第十关画面 穿过云朵升一级是要花6个金币的,有的时候金币真的很重要 前言 嗨喽,大家好呀!这里是魔王~ 一天晚上,天空中掉下一颗神奇的豌豆种子,正好落在了梦之森林的村长屋附近. 种子落地后吸收了池塘的水

  • 基于Python实现24点游戏的示例代码

    目录 1.前言 2.思路 3.代码 1.前言 24数大家之前玩过没有? 规则:一副扑克牌抽走大王,小王,K,Q,J(有的规则里面会抽走10,本文一律不抽走),之后在牌堆里随机抽取四张牌,将这四张牌加减乘除得到24. 如果再高级一点,还会有根号.阶乘.幂之类的算法,别问为啥不能幂运算,问就是懒,自己看思路自己实现去(bushi. 知识点:随机数,列表,嵌套判断,循环,死循环,都是新手接触的东西. 由于不能进行像根号,阶乘高级的运算,改版之后完全可以了. 话不多说,上思路 2.思路 1.随机生成四个

  • 基于Python实现成语填空游戏的示例代码

    目录 前言 一.环境准备 二.代码展示 三.效果展示 前言 成语填空想必大家都是十分熟悉的了,特别是有在上小学的家长肯定都有十分深刻的印象. 在我们的认知里看图猜成语不就是一些小儿科的东西吗? 当然了你也别小看了成语调控小游戏,有的时候知识储备不够,你还真的不一定猜得出来是什么?更重要的是有的时候给你这个提示你都看不懂,那你就拿他没办法.——小学语文必备 成语是小学语文非常重要的一个知识点,几乎是逢考必有,作为基础,自然是需要长期的积累,并且需要积累到一定的数量,有了一定的量才能够产生质变,对于

随机推荐