Pygame レベル/メニューの状態
Pygame は、2D ゲームを作成するための人気のある Python ライブラリです。グラフィック、サウンド、入力などを処理するためのさまざまなモジュールが提供されます。
この記事では、Pygame を使用して複数のレベルとメニューを持つゲームを作成する方法について説明します。まずは 1 つのレベルを持つ単純なゲームを作成し、次にそれを拡張して複数のレベルとメイン メニューを持つゲームを作成します。
1 つのレベルを持つ単純なゲームの作成
単一レベルの単純なゲームを作成するには、Pygame ウィンドウを作成し、いくつかのグラフィックをロードし、ゲーム ループを作成する必要があります。
コードは次のとおりです。これを行う方法を示すスニペット:
import pygame # Initialize the Pygame library pygame.init() # Set the window size SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 # Create the Pygame window screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) # Set the window title pygame.display.set_caption("My Game") # Load the background image background_image = pygame.image.load("background.png").convert() # Create the player sprite player = pygame.sprite.Sprite() player.image = pygame.image.load("player.png").convert() player.rect = player.image.get_rect() player.rect.center = (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2) # Create the enemy sprite enemy = pygame.sprite.Sprite() enemy.image = pygame.image.load("enemy.png").convert() enemy.rect = enemy.image.get_rect() enemy.rect.center = (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 + 100) # Create a group to hold all the sprites all_sprites = pygame.sprite.Group() all_sprites.add(player) all_sprites.add(enemy) # Create a clock to control the game loop clock = pygame.time.Clock() # Run the game loop running = True while running: # Process events for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Update the game state all_sprites.update() # Draw the game画面 screen.blit(background_image, (0, 0)) all_sprites.draw(screen) # Flip the display pygame.display.flip() # Cap the frame rate at 60 FPS clock.tick(60) # Quit the game pygame.quit()
このコードは、背景画像と 2 つのスプライト (プレイヤーと敵) を含む Pygame ウィンドウを作成します。ゲーム ループは、プレーヤーがゲームを終了するまで実行され、ループの各反復中に、ゲームの状態が更新され、画面が描画され、ディスプレイが反転されます。
複数のレベルとを含むようにゲームを拡張します。メイン メニュー
ゲームを拡張して複数のレベルとメイン メニューを含めるには、新しい Scene クラスを作成する必要があります。シーンは、レベルやメニューなど、ゲームの特定の部分を表します。
シーン クラスの作成方法を示すコード スニペットは次のとおりです。
class Scene: def __init__(self): self.next = None def update(self): pass def draw(self, screen): pass def handle_events(self, events): pass
シーン クラスには次のものがあります。 3 つのメソッド: update、draw、handle_events。 update メソッドはゲームの状態を更新するためにフレームごとに呼び出され、draw メソッドはゲーム画面を描画するためにフレームごとに呼び出され、handle_events メソッドはユーザー入力を処理するためにフレームごとに呼び出されます。
これで、各レベルとメインメニューの新しいシーン。これを行う方法を示すコード スニペットを次に示します。
class Level1(Scene): def __init__(self): super().__init__() # Create the player sprite self.player = pygame.sprite.Sprite() self.player.image = pygame.image.load("player.png").convert() self.player.rect = self.player.image.get_rect() self.player.rect.center = (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2) # Create the enemy sprite self.enemy = pygame.sprite.Sprite() self.enemy.image = pygame.image.load("enemy.png").convert() self.enemy.rect = self.enemy.image.get_rect() self.enemy.rect.center = (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 + 100) # Create a group to hold all the sprites self.all_sprites = pygame.sprite.Group() self.all_sprites.add(self.player) self.all_sprites.add(self.enemy) def update(self): # Update the game state self.all_sprites.update() def draw(self, screen): # Draw the game画面 screen.blit(background_image, (0, 0)) self.all_sprites.draw(screen) def handle_events(self, events): # Handle user input for event in events: if event.type == pygame.QUIT: # The user has quit the game pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: # The user has pressed the left arrow key self.player.rect.x -= 10 elif event.key == pygame.K_RIGHT: # The user has pressed the right arrow key self.player.rect.x += 10 elif event.key == pygame.K_UP: # The user has pressed the up arrow key self.player.rect.y -= 10 elif event.key == pygame.K_DOWN: # The user has pressed the down arrow key self.player.rect.y += 10 class MainMenu(Scene): def __init__(self): super().__init__() # Create the title text self.title_text = pygame.font.Font(None, 50) self.title_text_image = self.title_text.render("My Game", True, (255, 255, 255)) self.title_text_rect = self.title_text_image.get_rect() self.title_text_rect.center = (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2) # Create the start button self.start_button = pygame.draw.rect(screen, (0, 255, 0), (SCREEN_WIDTH / 2 - 50, SCREEN_HEIGHT / 2 + 100, 100, 50)) def update(self): pass def draw(self, screen): # Draw the game画面 screen.blit(background_image, (0, 0)) screen.blit(self.title_text_image, self.title_text_rect) pygame.draw.rect(screen, (0, 255, 0), self.start_button) def handle_events(self, events): # Handle user input for event in events: if event.type == pygame.QUIT: # The user has quit the game pygame.quit() sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: # The user has clicked the start button if self.start_button.collidepoint(event.pos): # Set the next scene to Level1 self.next = Level1()
これで、さまざまなシーンを管理するための新しい SceneManager クラスを作成できるようになりました。 SceneManager は現在のシーンを追跡し、現在のシーンが終了すると次のシーンに切り替えます。
SceneManager クラスの作成方法を示すコード スニペットは次のとおりです。
class SceneManager: def __init__(self): self.current_scene = MainMenu() def run(self): # Run the game loop running = True while running: # Process events for event in pygame.event.get(): if event.type == pygame.QUIT: # The user has quit the game running = False # Update the current scene self.current_scene.update() # Draw the current scene self.current_scene.draw(screen) # Flip the display pygame.display.flip() # Check if the current scene is finished if self.current_scene.next is not None:
以上が複数のレベルとメインメニューを持つ Pygame ゲームを作成するには?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

pythonisbothcompiledinterted.whenyourunapythonscript、itisfirstcompiledintobytecode、これはdenepythonvirtualmachine(pvm).thishybridapproaChallowsforplatform-platform-denodent-codebutcututicut。

Pythonは厳密に行ごとの実行ではありませんが、最適化され、インタープレーターメカニズムに基づいて条件付き実行です。インタープリターは、コードをPVMによって実行されるBytecodeに変換し、定数式または最適化ループを事前促進する場合があります。これらのメカニズムを理解することで、コードを最適化し、効率を向上させることができます。

Pythonに2つのリストを接続する多くの方法があります。1。オペレーターを使用しますが、これはシンプルですが、大きなリストでは非効率的です。 2。効率的ですが、元のリストを変更する拡張メソッドを使用します。 3。=演算子を使用します。これは効率的で読み取り可能です。 4。itertools.chain関数を使用します。これはメモリ効率が高いが、追加のインポートが必要です。 5。リストの解析を使用します。これはエレガントですが、複雑すぎる場合があります。選択方法は、コードのコンテキストと要件に基づいている必要があります。

Pythonリストをマージするには多くの方法があります。1。オペレーターを使用します。オペレーターは、シンプルですが、大きなリストではメモリ効率的ではありません。 2。効率的ですが、元のリストを変更する拡張メソッドを使用します。 3. Itertools.chainを使用します。これは、大規模なデータセットに適しています。 4.使用 *オペレーター、1つのコードで小規模から中型のリストをマージします。 5. numpy.concatenateを使用します。これは、パフォーマンス要件の高い大規模なデータセットとシナリオに適しています。 6.小さなリストに適したが、非効率的な追加方法を使用します。メソッドを選択するときは、リストのサイズとアプリケーションのシナリオを考慮する必要があります。

compiledlanguagesOfferspeedandsecurity、foredlanguagesprovideeaseofuseandportability.1)compiledlanguageslikec arefasterandsecurebuthavelOnderdevelopmentsplat dependency.2)

Pythonでは、forループは反復可能なオブジェクトを通過するために使用され、条件が満たされたときに操作を繰り返し実行するためにしばらくループが使用されます。 1)ループの例:リストを通過し、要素を印刷します。 2)ループの例:正しいと推測するまで、数値ゲームを推測します。マスタリングサイクルの原則と最適化手法は、コードの効率と信頼性を向上させることができます。

リストを文字列に連結するには、PythonのJoin()メソッドを使用して最良の選択です。 1)join()メソッドを使用して、 '' .join(my_list)などのリスト要素を文字列に連結します。 2)数字を含むリストの場合、連結する前にマップ(str、数字)を文字列に変換します。 3) '、'などの複雑なフォーマットに発電機式を使用できます。 4)混合データ型を処理するときは、MAP(STR、Mixed_List)を使用して、すべての要素を文字列に変換できるようにします。 5)大規模なリストには、 '' .join(lage_li)を使用します

pythonusesahybridapproach、コンコイリティレーショントビテコードと解釈を組み合わせて、コードコンピレッドフォームと非依存性bytecode.2)


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

SecLists
SecLists は、セキュリティ テスターの究極の相棒です。これは、セキュリティ評価中に頻繁に使用されるさまざまな種類のリストを 1 か所にまとめたものです。 SecLists は、セキュリティ テスターが必要とする可能性のあるすべてのリストを便利に提供することで、セキュリティ テストをより効率的かつ生産的にするのに役立ちます。リストの種類には、ユーザー名、パスワード、URL、ファジング ペイロード、機密データ パターン、Web シェルなどが含まれます。テスターはこのリポジトリを新しいテスト マシンにプルするだけで、必要なあらゆる種類のリストにアクセスできるようになります。

mPDF
mPDF は、UTF-8 でエンコードされた HTML から PDF ファイルを生成できる PHP ライブラリです。オリジナルの作者である Ian Back は、Web サイトから「オンザフライ」で PDF ファイルを出力し、さまざまな言語を処理するために mPDF を作成しました。 HTML2FPDF などのオリジナルのスクリプトよりも遅く、Unicode フォントを使用すると生成されるファイルが大きくなりますが、CSS スタイルなどをサポートし、多くの機能強化が施されています。 RTL (アラビア語とヘブライ語) や CJK (中国語、日本語、韓国語) を含むほぼすべての言語をサポートします。ネストされたブロックレベル要素 (P、DIV など) をサポートします。

メモ帳++7.3.1
使いやすく無料のコードエディター

MantisBT
Mantis は、製品の欠陥追跡を支援するために設計された、導入が簡単な Web ベースの欠陥追跡ツールです。 PHP、MySQL、Web サーバーが必要です。デモおよびホスティング サービスをチェックしてください。

PhpStorm Mac バージョン
最新(2018.2.1)のプロフェッショナル向けPHP統合開発ツール
