複数のレベルとメインメニューを持つ Pygame ゲームを作成するには?
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 サイトの他の関連記事を参照してください。

ホットAIツール

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

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

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

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

人気の記事

ホットツール

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

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック











Pythonは学習と使用が簡単ですが、Cはより強力ですが複雑です。 1。Python構文は簡潔で初心者に適しています。動的なタイピングと自動メモリ管理により、使いやすくなりますが、ランタイムエラーを引き起こす可能性があります。 2.Cは、高性能アプリケーションに適した低レベルの制御と高度な機能を提供しますが、学習しきい値が高く、手動メモリとタイプの安全管理が必要です。

Pythonを1日2時間学ぶだけで十分ですか?それはあなたの目標と学習方法に依存します。 1)明確な学習計画を策定し、2)適切な学習リソースと方法を選択します。3)実践的な実践とレビューとレビューと統合を練習および統合し、統合すると、この期間中にPythonの基本的な知識と高度な機能を徐々に習得できます。

Pythonは開発効率でCよりも優れていますが、Cは実行パフォーマンスが高くなっています。 1。Pythonの簡潔な構文とリッチライブラリは、開発効率を向上させます。 2.Cのコンピレーションタイプの特性とハードウェア制御により、実行パフォーマンスが向上します。選択を行うときは、プロジェクトのニーズに基づいて開発速度と実行効率を比較検討する必要があります。

PythonとCにはそれぞれ独自の利点があり、選択はプロジェクトの要件に基づいている必要があります。 1)Pythonは、簡潔な構文と動的タイピングのため、迅速な開発とデータ処理に適しています。 2)Cは、静的なタイピングと手動メモリ管理により、高性能およびシステムプログラミングに適しています。

PythonListSarePartOfThestAndardarenot.liestareBuilting-in、versatile、forStoringCollectionsのpythonlistarepart。

Pythonは、自動化、スクリプト、およびタスク管理に優れています。 1)自動化:OSやShutilなどの標準ライブラリを介してファイルバックアップが実現されます。 2)スクリプトの書き込み:Psutilライブラリを使用してシステムリソースを監視します。 3)タスク管理:スケジュールライブラリを使用してタスクをスケジュールします。 Pythonの使いやすさと豊富なライブラリサポートにより、これらの分野で優先ツールになります。

科学コンピューティングにおけるPythonのアプリケーションには、データ分析、機械学習、数値シミュレーション、視覚化が含まれます。 1.numpyは、効率的な多次元配列と数学的関数を提供します。 2。ScipyはNumpy機能を拡張し、最適化と線形代数ツールを提供します。 3. Pandasは、データ処理と分析に使用されます。 4.matplotlibは、さまざまなグラフと視覚的な結果を生成するために使用されます。

Web開発におけるPythonの主要なアプリケーションには、DjangoおよびFlaskフレームワークの使用、API開発、データ分析と視覚化、機械学習とAI、およびパフォーマンスの最適化が含まれます。 1。DjangoandFlask Framework:Djangoは、複雑な用途の迅速な発展に適しており、Flaskは小規模または高度にカスタマイズされたプロジェクトに適しています。 2。API開発:フラスコまたはdjangorestFrameworkを使用して、Restfulapiを構築します。 3。データ分析と視覚化:Pythonを使用してデータを処理し、Webインターフェイスを介して表示します。 4。機械学習とAI:Pythonは、インテリジェントWebアプリケーションを構築するために使用されます。 5。パフォーマンスの最適化:非同期プログラミング、キャッシュ、コードを通じて最適化
