国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Python自制“超級馬里奧”小游戲

這篇具有很好參考價值的文章主要介紹了Python自制“超級馬里奧”小游戲。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

?作者簡介:華為開發(fā)者聯(lián)盟優(yōu)質內容創(chuàng)作者、CSDN內容合伙人、GitHub專業(yè)技術人員??
??個人主頁:北雨·寒冰~?的CSDN博客
??系列專欄:PyGame
??個人格言:書山有路勤為徑,學海無涯苦作舟

?python馬里奧游戲代碼,PyGame,Python,小游戲開發(fā),python,pygame,開發(fā)語言

python馬里奧游戲代碼,PyGame,Python,小游戲開發(fā),python,pygame,開發(fā)語言

目錄

前言

看效果

1.基礎設置(tools部分)

2.設置背景音樂以及場景中的文字(setup部分)

3.設置游戲規(guī)則(load_screen)

4.設置游戲內菜單等(main_menu)

5.main()

6.調用以上函數(shù)實現(xiàn)


前言

最近在家上網課,閑得無聊,就想到用PyGame包自制一個“超級馬里奧”的小游戲,在同學面前秀一手。

今天,寒冰就帶大家來看看“超級馬里奧”的全編寫過程!

(當然pip install pygame應該不用我說了吧。。。)

也闊以“直接跳到文末”下載資源?。?!

看效果

python馬里奧游戲代碼,PyGame,Python,小游戲開發(fā),python,pygame,開發(fā)語言

?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.設置游戲規(guī)則(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.調用以上函數(shù)實現(xiàn)

import sys
import pygame as pg
from 小游戲.超級瑪麗.data.main import main
import cProfile
 
 
if __name__=='__main__':
    main()
    pg.quit()
    sys.exit()

在這里主要給大家展示主體的代碼,完整資源戳我領?。?!

結束語?

今天的分享就到這里啦~,感謝你的觀看,拜拜嘍~

python馬里奧游戲代碼,PyGame,Python,小游戲開發(fā),python,pygame,開發(fā)語言文章來源地址http://www.zghlxwxcb.cn/news/detail-824114.html

到了這里,關于Python自制“超級馬里奧”小游戲的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!

本文來自互聯(lián)網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。如若轉載,請注明出處: 如若內容造成侵權/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經查實,立即刪除!

領支付寶紅包贊助服務器費用

相關文章

  • pygame自制小游戲

    pygame自制小游戲

    pygame——游戲視頻 簡單的來寫一個pygame小游戲,我的畫面比較卡哇伊各位可以自己換圖片哈。 就是一個最基本的pygame小游戲,可以控制人物,攻擊敵人,打到敵人使敵人消失,如果敵人到達邊緣仍然沒有被消滅,游戲就會失敗。 1.鼠標移動人物跟隨移動,播放背景音樂,可以摁下

    2024年02月11日
    瀏覽(44)
  • 【Cocos 3d】從零開始自制3d出租車小游戲

    【Cocos 3d】從零開始自制3d出租車小游戲

    本文很長,建議收藏食用。 課程來源: 游戲開發(fā)教程 | 零基礎也可以用18堂課自制一款3D小游戲 | Cocos Creator 3D 中文教程(合集)p1~p6 簡介: 資源下載:https://github.com/cocos-creator/tutorial-taxi-game 適合學習人群:本教程假定你對編程有一定的了解,ts,js 學習過其中之一。 如果不

    2024年02月02日
    瀏覽(54)
  • Java小游戲練習---超級瑪麗代碼實現(xiàn)

    Java小游戲練習---超級瑪麗代碼實現(xiàn)

    B站教學視頻: 01_超級瑪麗_創(chuàng)建窗口_嗶哩嗶哩_bilibili 素材提取: 【超級會員V2】我通過百度網盤分享的文件:Java游戲項目… 鏈接:百度網盤 請輸入提取碼 提取碼:k6j1 復制這段內容打開「百度網盤APP 即可獲取」 百度網盤 請輸入提取碼 百度網盤為您提供文件的網絡備份、同

    2024年02月06日
    瀏覽(22)
  • Java超級瑪麗小游戲制作過程講解 第六天 繪制背景

    我們新建一個BackGround類。 這段代碼是一個名為`BackGround`的Java類,用于表示背景圖像和場景。它具有以下屬性和方法: 1. `bgImage`:表示當前場景要顯示的圖像的`BufferedImage`對象。 2. `sort`:記錄當前是第幾個場景的整數(shù)值。 3. `flag`:判斷是否是最后一個場景的布爾值。 構造方

    2024年02月13日
    瀏覽(49)
  • Java超級瑪麗小游戲制作過程講解 第五天 創(chuàng)建并完成常量類04

    今天繼續(xù)完成常量的創(chuàng)建。 這段代碼是用于加載游戲中的圖片資源。代碼使用了Java的ImageIO類來讀取圖片文件,并將其添加到相應的集合中。 首先,代碼創(chuàng)建了一個`obstacle`列表,用于存儲障礙物的圖片資源。然后,使用try-catch語句塊來捕獲可能發(fā)生的IO異常。 在try塊中,通

    2024年02月14日
    瀏覽(16)
  • Java超級瑪麗小游戲制作過程講解 第三天 創(chuàng)建并完成常量類02

    今天我們繼續(xù)完成常量類的創(chuàng)建! 定義了一個名為 `obstacle` 的靜態(tài)變量,它的類型是 `ListBufferedImage` ,即一個存儲 `BufferedImage` 對象的列表。 - `obstacle`: 這是一個列表(List)類型的變量,用于存儲多個障礙物的圖像。列表是一種數(shù)據(jù)結構,可以容納多個元素,并且具有動態(tài)

    2024年02月14日
    瀏覽(86)
  • python簡單小游戲代碼教程,python編程小游戲代碼

    python簡單小游戲代碼教程,python編程小游戲代碼

    大家好,本文將圍繞一些簡單好玩的python編程游戲展開說明,python編寫的入門簡單小游戲是一個很多人都想弄明白的事情,想搞清楚python簡單小游戲代碼教程需要先了解以下幾個事情。 Source code download: 本文相關源碼 大家好,我是辣條。 今天給大家?guī)?0個py小游戲,一定要

    2024年02月03日
    瀏覽(109)
  • python超簡單小游戲代碼,python簡單小游戲代碼

    python超簡單小游戲代碼,python簡單小游戲代碼

    大家好,小編來為大家解答以下問題,python超簡單小游戲代碼,python簡單小游戲代碼,今天讓我們一起來看看吧! 大家好,我是辣條。 今天給大家?guī)?0個py小游戲,一定要收藏! 目錄 有手就行 1、吃金幣 2、打乒乓 3、滑雪 4、并夕夕版飛機大戰(zhàn) 5、打地鼠 簡簡單單 6、小恐

    2024年03月14日
    瀏覽(102)
  • python簡單小游戲代碼100行,python小游戲代碼大全

    python簡單小游戲代碼100行,python小游戲代碼大全

    大家好,給大家分享一下python簡單小游戲代碼100行,很多人還不知道這一點。下面詳細解釋一下?,F(xiàn)在讓我們來看看! download: python小游戲代碼 按照題目要求編寫燃悔中的Python程序如下 import random numlist=random.sample(range(0,10),5) while numlist[0]==0: ? ? numlist=random.sample(range(0,10),5) n

    2024年02月08日
    瀏覽(29)
  • python入門小游戲代碼20行,python小游戲代碼大全

    python入門小游戲代碼20行,python小游戲代碼大全

    大家好,給大家分享一下python簡單小游戲代碼20行,很多人還不知道這一點。下面詳細解釋一下。現(xiàn)在讓我們來看看! 01 整體框架 平臺:pycharm 關于pygame的安裝這里就不在贅述,大家自行上網找合適自己的版本的安裝即可。關于pygame模塊知識會穿插在下面代碼中介紹,用到什

    2024年04月22日
    瀏覽(24)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領取紅包,優(yōu)惠每天領

二維碼1

領取紅包

二維碼2

領紅包