使用 Arcade 库进行 2D 游戏入门(第11部分):在屏幕之间切换
发布: (2025年12月24日 GMT+8 20:11)
3 min read
原文: Dev.to
Source: Dev.to
组织文件
随着开发的进行,源文件数量增加,管理变得更困难。
创建一个专用的 src 文件夹用于源代码,并将屏幕拆分为三个模块,每个屏幕一个。
| 文件名 | 角色 | 位置 |
|---|---|---|
title.py | 标题屏幕 | src/title.py |
game.py | 游戏屏幕 | src/game.py |
result.py | 结果屏幕 | src/result.py |
文件夹结构如下:
# Folder structure
working_directory/
├─ main.py
├─ images/
└─ src/ # Folder for source code
├─ title.py
├─ game.py
└─ result.py
切换屏幕
切换屏幕的代码与之前的示例相同。
在任何需要进行屏幕切换的地方,只需:
- 创建一个
arcade.View。 - 将其传递给
window.show_view()。
# main.py (example)
view = title.TitleView(window) # TitleView
window.show_view(view)
Source: …
完整代码
下面是一个完整可运行的示例。按 SPACE 键可以按以下顺序切换屏幕:
标题屏幕 → 游戏屏幕 → 结果屏幕
你可以直接复制并运行这些代码。
main.py
import arcade
import src.title as title
def main():
"""Main process"""
window = arcade.Window(480, 320, "Hello, Arcade!!")
view = title.TitleView(window) # TitleView
window.show_view(view)
arcade.run()
if __name__ == "__main__":
main()
src/title.py
import arcade
import src.game as game
# Title screen
class TitleView(arcade.View):
def __init__(self, window):
super().__init__()
self.window = window
self.background_color = arcade.color.PRUNE
# Info text
self.msg_info = arcade.Text(
"TITLE: SPACE TO NEXT",
window.width / 2, window.height - 20,
arcade.color.WHITE, 12,
anchor_x="center", anchor_y="top"
)
def on_key_press(self, key, key_modifiers):
# SPACE → Game screen
if key == arcade.key.SPACE:
view = game.GameView(self.window) # GameView
self.window.show_view(view)
def on_update(self, delta_time):
pass
def on_draw(self):
self.clear()
self.msg_info.draw()
src/game.py
import arcade
import src.result as result
# Game screen
class GameView(arcade.View):
def __init__(self, window):
super().__init__()
self.window = window
self.background_color = arcade.color.DARK_SPRING_GREEN
# Info text
self.msg_info = arcade.Text(
"GAME: SPACE TO NEXT",
window.width / 2, window.height - 20,
arcade.color.WHITE, 12,
anchor_x="center", anchor_y="top"
)
def on_key_press(self, key, key_modifiers):
# SPACE → Result screen
if key == arcade.key.SPACE:
view = result.ResultView(self.window) # ResultView
self.window.show_view(view)
def on_update(self, delta_time):
pass
def on_draw(self):
self.clear()
self.msg_info.draw()
src/result.py
import arcade
import src.title as title
# Result screen
class ResultView(arcade.View):
def __init__(self, window):
super().__init__()
self.window = window
self.background_color = arcade.color.CERULEAN
# Info text
self.msg_info = arcade.Text(
"RESULT: SPACE TO NEXT",
window.width / 2, window.height - 20,
arcade.color.WHITE, 12,
anchor_x="center", anchor_y="top"
)
def on_key_press(self, key, key_modifiers):
# SPACE → Title screen
if key == arcade.key.SPACE:
view = title.TitleView(self.window) # TitleView
self.window.show_view(view)
def on_update(self, delta_time):
pass
def on_draw(self):
self.clear()
self.msg_info.draw()
运行后效果如下:
最后思考
非常感谢阅读。
我希望本系列能成为你自己游戏开发之旅的起点。ޱ(ఠ皿ఠ)ว👍
