Fastgame是我自己开发的游戏库,把自己的文档CV下:
一、Fastgame用前提示
fastgame支持的文件格式
图片:
- JPG
- PNG
- GIF(无动图)
- BMP
- SVG(有缩放错误)
- WEBP(有缩放错误)
- PCX
- TGA
- TIF
- LBM
- XPM
视频:
- MP4
- AVI
- FIV
音频:
- OGG
- WAV(未压缩)
- MP3(需要有FFMpeg运行环境)
fastgame设计思想
参考了pyglet
的装饰器和scratch
的事件驱动模式。
fastgame坐标系
一切坐标都以对象的矩形左上角为原点。
窗口的(0, 0)点为窗口左上角。
fastgame适合的程序
- 图片2D游戏。
- 画布像素2D游戏。
- 简单的、需要特殊效果的GUI界面。
二、Fastgame模块详解
fastgame.api
fastgame的各类API。
底层模块。
fastgame.__main__
通过命令行检测fastgame安装,及查看fastgame版本:
fastgame -v
也可以:
fastgame version
fastgame.exceptions
fastgame的各个异常。
fastgame.exceptions.FastGameError
fastgame异常基类。
fastgame.exceptions.CannotImportError
fastgame未能导入模块异常。
fastgame.exceptions.EngineError
fastgame音频播放引擎异常。
fastgame.exceptions.NotCreatedGameError
未创建fastgame游戏错误。
fastgame.exceptions.OutOfCanvasError
fastgame画笔路径超出画布异常。
fastgame.exceptions.NotPolygonError
fastgame非几何多边形异常。
fastgame.exceptions.StyleNotFoundError
fastgame风格不存在异常。
fastgame.exceptions.JoystickError
fastgame游戏手柄异常。
fastgame.exceptions.VideoError
fastgame视频组件异常。
fastgame.locals
定义了Fastgame常用的常量。
from fastgame.locals import *
fastgame.version
Fastgame版本系统。
fastgame.version.major
Fastgame主版本号。
fastgame.version.minor
Fastgame次版本号。
fastgame.version.micro
Fastgame微版本号。
fastgame.version.vernum
Fastgame版本元组。
等价于(major, minor, micro)
实例:
from fastgame.version import vernum
if vernum < (1, 0, 0):
raise SystemExit
fastgame.version.version
Fastgame版本字符串。
等于fastgame -v
的结果。
import fastgame
from fastgame.version import version
if fastgame.__version__ != version:
raise SystemExit
fastgame.core.game
Fastgame主要游戏文件。
fastgame.core.game.FastGame
Fastgame游戏类。
fastgame.core.game.FastGame()
用法:
FastGame(
title: str = 'Fast Game Window',
size: Tuple[int, int] = (500, 500),
style: int = NORMAL,
depth: int = 0,
icon: str = None,
fps: int = 16,
debug_messages: bool = False,
init_pygame: bool = True
)
参数说明:
title
: 游戏窗口的标题。size
: 游戏窗口的大小。第一个值为长,第二个值为宽。设为(0, 0)时,大小与屏幕大小相同。style
: 游戏窗口风格。
风格 | 效果 |
---|---|
fastgame.NORMAL | 正常窗口 |
fastgame.FULLSCREEN | 全屏窗口 |
fastgame.RESIZEABLE | 可缩放窗口 |
fastgame.NO_FRAME | 无边框窗口 |
风格允许使用 |
运算符。
实例(无边框+可缩放)
import fastgame
from fastgame.locals import *
game = fastgame.FastGame(style=NO_FRAME | RESIZEABLE)
depth
: 游戏窗口位深。设为0则自动调整。icon
: 游戏窗口图标。可以使用fastgame支持的图像格式。
不支持ico格式!fps
: 每秒刷新帧数,即每秒显示几张图片,支持浮点数。debug_messages
: 是否进入调试模式,进入后有日志信息。init_pygame
: 是否自动初始化pygame
。建议设为True
。
fastgame.core.game.FastGame.mouse_position
mouse_position
是FastGame类的虚拟属性。
获取鼠标位置:
from fastgame import FastGame
game = FastGame()
x, y = game.mouse_position
设置鼠标位置(将鼠标移动至):
from fastgame import FastGame
game = FastGame()
game.mouse_position = (100, 100)
fastgame.core.game.FastGame.mouse_rel
获取鼠标在调用此虚拟属性前的一系列移动。
如下是一个返回的例子:
[(0, 0), (1, 0), (1, 1)]
实例:
from fastgame import FastGame
game = FastGame()
@game.update
def update():
print(game.mouse_rel)
game.mainloop()
fastgame.core.game.FastGame.hide_mouse
隐藏鼠标指针。
实例1(隐藏鼠标指针):
from fastgame import FastGame
game = FastGame()
game.hide_mouse() # 方法1
FastGame.hide_mouse() # 方法2
实例2(设置鼠标光标):
from fastgame import FastGame, Sprite
game = FastGame()
cursor = Sprite('cursor.png') # cursor.png是鼠标光标图片
game.hide_mouse()
@game.update
def update():
cursor.update()
cursor.move_to_mouse()
game.mainloop()
fastgame.core.game.FastGame.show_mouse
显示鼠标指针。
实例(显示鼠标指针):
from fastgame import FastGame
game = FastGame()
game.show_mouse() # 方法1
FastGame.show_mouse() # 方法2
fastgame.core.game.FastGame.wm_info
获得系统的窗口信息。
由操作系统而定。
返回一个由操作系统填充数据的字典。
一些操作系统可能不会往里边填充信息,则返回一个空字典。大多数平台将返回一个"window"键,对应的值是当前显示界面的系统ID。
fastgame.core.game.FastGame.check_rate
用法:
FastGame.check_rate(rate)
检测当前的循环次数是否除以rate为0.
这可以用于一定频率地进行某操作。
实例(显示角色):
from fastgame import FastGame, Sprite
game = FastGame()
sprite = Sprite('test.png')
sprite.hide()
sprites = []
@game.update
def update():
if game.check_rate(10):
spr = sprite.clone()
spr.show()
sprites.append(spr)
for spr in sprites:
spr.update()
game.mainloop()
fastgame.core.game.FastGame.destroy
关闭窗口后结束此python程序。
若只是关闭窗口,将参数close_program设为False即可,但可能引发BUG。
会在关闭窗口后调用被FastGame.when_end装饰过的函数。
用法:
FastGame.destroy(
status: int = 0,
close_program: bool = True,
*args, **kwargs
)
参数详解:
status
: 关闭状态码。close_program
: 是否结束此python程序。args
、kwargs
: 关闭前调用的when-end函数的形参。
fastgame.core.game.FastGame.toggle_debug
切换调试模式。
fastgame.core.game.FastGame.toggle_fullscreen
切换全屏模式。
fastgame.core.game.FastGame.get_counter
获取当前循环的次数。
返回值为int
型。
fastgame.core.game.FastGame.title
窗口标题。
是一个虚拟属性。
实例:
from fastgame import FastGame
game = FastGame()
print(game.title) # 获取窗口标题
game.title = 'Hello World' # 设置窗口标题
fastgame.core.game.FastGame.when_start
装饰器,装饰开始循环前的函数。
Fastgame的设计思想参考了Scratch3,仿照了一些事件驱动模式。
fastgame.core.game.FastGame.when_end
装饰器,装饰关闭窗口前的函数。
具体调用位置在关闭窗口后,退出pygame前。
fastgame.core.game.FastGame.on_mouse_down
装饰器,装饰鼠标按下时回调的函数。
获取鼠标按钮使用Fastgame.event.get('button')
fastgame.core.game.FastGame.on_mouse_up
装饰器,装饰鼠标放开时回调的函数。
fastgame.core.game.FastGame.on_mouse_move
装饰器,装饰鼠标移动时回调的函数。
fastgame.core.game.FastGame.on_key_down
装饰器,装饰任意按键按下时回调的函数。
fastgame.core.game.FastGame.on_key_up
装饰器,装饰任意按键放开时回调的函数。
fastgame.core.game.FastGame.update
装饰器,装饰显示角色的回调函数。
本函数是渲染游戏画面必需的。
fastgame.core.game.FastGame.mainloop
进入窗口显示的主循环。
会阻塞程序的运行。
用法:
FastGame.mainloop(
status: int = 0,
escape_quit: bool = False,
render_all: bool = False
)
参数详解:
status
: 程序退出时的状态码escape_quit
: 用户按下ESC键时,是否关闭窗口。render_all
: 更新窗口时,是否渲染所有部分,或只渲染有变化的部分。
注:在正常情况下,建议将render_all
参数设为False,可以获得更高的性能。
fastgame.core.sprite
Fastgame主要角色模块。
fastgame.core.sprite.Sprite
Fastgame主要角色类。
继承自pygame.sprite.Sprite
fastgame.core.sprite.Sprite()
用法:
Sprite(
image: str,
size: Union[None, Tuple[int, int]] = None
)
参数详解:
image
: 角色图片文件。size
: 若不为None
,即为缩放后角色图片大小。
image参数支持导入./
和./resources/images
的图片,如下项目结构:
testgame
│ game.py
│
└─resources
└─images
│ test.png
支持下面的导入方案:
from fastgame import Sprite
sprite = Sprite('test.png')
fastgame.core.sprite.Sprite.position
角色位置,一个虚拟属性。
实例:
from fastgame import FastGame, Sprite
game = FastGame()
sprite = Sprite('test.png')
print(sprite.position) # 获取角色位置
sprite.position = (100, 100) # 设置角色位置
fastgame.core.sprite.Sprite.update
在窗口上更新此角色。
必须在被Fastgame.update装饰过的函数中调用。
fastgame.core.sprite.Sprite.collide_other
检测此角色是否碰到了另一角色。
判断方法基于两个角色的矩形碰撞。
当有非长方形的角色参与检测,会出现没有碰撞,检测却是已经碰撞的情况。
用法:
Sprite.collide_other(sprite: Sprite)
参数sprite
: 另一个角色对象。
fastgame.core.sprite.Sprite.collide_mouse
检测此角色是否碰到了鼠标指针。
判断方法基于角色矩形。
当非长方形的角色参与检测,会出现没有碰撞,检测却是已经碰撞的情况。
fastgame.core.sprite.Sprite.collide_edge
检测此角色是否碰到了边缘。
判断方法基于角色矩形。
当非长方形的角色参与检测,会出现看似没有碰撞,检测却是碰撞的情况。
返回值为一个二元组,第一个值为是否碰撞左右边缘,第二个值为是否碰撞上下边缘。
实例:
from fastgame import FastGame, Sprite
game = FastGame()
sprite = Sprite('test.png')
collide_left_or_right, collide_up_or_down = sprite.collide_edge()
fastgame.core.sprite.Sprite.move_to_mouse
移动至鼠标指针的位置。
fastgame.core.sprite.Sprite.add_x
增加X坐标。
用法:
Sprite.add_x(add: int)
参数add
: 增加的X坐标,可以为负数。
将add设为负数即为减少X坐标。
fastgame.core.sprite.Sprite.add_y
增加Y坐标。
用法:
Sprite.add_y(add: int)
参数add
: 增加的Y坐标,可以为负数。
将add设为负数即为减少Y坐标。
fastgame.core.sprite.Sprite.set_x
设置X坐标。
用法:
Sprite.set_x(x: int)
参数x
: X坐标。
fastgame.core.sprite.Sprite.set_y
设置Y坐标。
用法:
Sprite.set_y(y: int)
参数y
: Y坐标。
fastgame.core.sprite.Sprite.move_to
移动至某点。
用法:
Sprite.move_to(x: int, y: int)
参数详解:
x
: X坐标。y
: Y坐标。
Sprite.move_to(x, y)
等价于Sprite.position = (x, y)
fastgame.core.sprite.Sprite.clone
创建克隆体。
克隆体的位置于此角色的位置相同。
本方法的概念不同于Scratch
的克隆体,而是相当于copy
方法。
fastgame.core.sprite.Sprite.hide
隐藏此角色。
也可以在update中进行条件判断,如下:
@game.update
def update():
if something:
sprite.update()
fastgame.core.sprite.Sprite.show
显示此角色。
在update中更新才有效。
fastgame.core.sprite.Sprite.resize
缩放此角色的图片。
WEBP
、SVG
等图片可能错位。
用法:
Sprite.resize(size: Tuple[int, int])
参数size
: 图片大小。
fastgame.core.sprite.Sprite.set_image
重置此角色的图片。
重设的图片对克隆体无效。
用法:
Sprite.set_image(
image: str,
size: Tuple[int, int] = None
)
参数详解:
image
: 角色图片文件。size
: 若不为None
,即为缩放后角色图片大小。
fastgame.core.sprite.Sprite.image
属性值,角色对应的pygame.Surface
对象。
底层pygame兼容接口。
fastgame.core.sprite.Sprite.rect
属性值,角色对应的pygame.rect.Rect
对象。
底层pygame兼容接口。
代码 | 意义 |
---|---|
Sprite.rect.x | 角色X坐标 |
Sprite.rect.y | 角色Y坐标 |
Sprite.rect.size | 角色大小 |
Sprite.rect.width | 角色长 |
Sprite.rect.height | 角色宽 |
Sprite.rect.center | 角色中心点 |
Sprite.rect.centerx | 角色中心点X坐标 |
Sprite.rect.centery | 角色中心点Y坐标 |
Sprite.rect.right | 角色右部坐标 |
Sprite.rect.bottom | 角色底部坐标 |
Sprite.rect.bottomleft | 角色左下角位置 |
Sprite.rect.bottomright | 角色右下角位置 |
Sprite.rect.topleft | 角色左上角位置 |
Sprite.rect.topright | 角色右上角位置 |
Sprite.rect.midtop | 角色顶部中点位置 |
Sprite.rect.midbottom | 角色底部中点位置 |
Sprite.rect.midleft | 角色左部中点位置 |
Sprite.rect.midright | 角色右部中点位置 |
fastgame.utils.color
Fastgame颜色模块。
fastgame.utils.color.Color
Fastgame颜色基类。
继承自pygame.Color
。
fastgame.utils.color.Color()
用法:
Color(
*args: Union[str, Tuple[int, int, int], Tuple[int, int, int, int]],
color_type=RGB
)
参数详解:
args
: 列表参数,支持如(0, 0, 0)
、0, 0, 0
和"#FFFFFF"
等的输入模式。color_type
: 必须使用关键字模式传参,颜色的类型。
支持的颜色类型:
- RGB, RGBA
- HEX
- CMYK
- HSV, HSVA
- HSL, HSLA
颜色类型通过from fastgame.locals import *
导入。
fastgame.utils.color的收录颜色
目前收录颜色:
颜色 | 代码 |
---|---|
白色 | fastgame.utils.color.WHITE |
黑色 | fastgame.utils.color.BLACK |
红色 | fastgame.utils.color.RED |
绿色 | fastgame.utils.color.GREEN |
蓝色 | fastgame.utils.color.BLUE |
棕色 | fastgame.utils.color.BROWN |
银色 | fastgame.utils.color.SLIVER |
灰色 | fastgame.utils.color.GRAY |
粉色 | fastgame.utils.color.PINK |
紫色 | fastgame.utils.color.PURPLE |
粉色 | fastgame.utils.color.PINK |
藏青色 | fastgame.utils.color.NAVY |
青色 | fastgame.utils.color.CYAN |
蓝绿色 | fastgame.utils.color.TEAL |
米黄色 | fastgame.utils.color.BEIGE |
金色 | fastgame.utils.color.GOLD |
橙色 | fastgame.utils.color.ORANGE |
黄褐色 | fastgame.utils.color.TAN |
土黄色 | fastgame.utils.color.KHAKI |
黄色 | fastgame.utils.color.YELLOW |
fastgame.utils.joystick
Fastgame游戏手柄模块。
在一些环境中不支持。
注意:实验功能,可能在接下来的版本中删除,导致不兼容!
fastgame.utils.joystick.Joystick
Fastgame游戏手柄类。
fastgame.utils.joystick.Joystick()
Joystick(
joystick_id: int,
init_joystick: bool = True
)
参数详解:
joystick_id
: 游戏手柄ID号。init_joystick
: 是否自动初始化pygame.joystick
。
fastgame.utils.joystick.Joystick.id
属性值。游戏手柄ID号。
fastgame.utils.joystick.Joystick.guid
属性值。游戏手柄GUID号。
fastgame.utils.joystick.Joystick.name
属性值。游戏手柄名称。
fastgame.utils.joystick.Joystick.devices
属性值。游戏手柄装置数。
fastgame.utils.joystick.Joystick.axes
属性值。游戏手柄球数。
fastgame.utils.joystick.Joystick.start_rumble
使游戏手柄发出持续而低沉的声音。
如果成功播放,则返回True,如果操纵杆不支持,则返回False.
用法:
Joystick.start_rumble(
low_frequency: float,
high_frequency: float,
duration: int
)
参数详解:
low_frequency
: 最低频率。high_frequency
: 最高频率。duration
: 持续时间。
fastgame.utils.joystick.Joystick.stop_rumble
停止任何持续而低沉的声音。
fastgame.utils.joystick.Joystick.all_joysticks_id
静态方法。
返回所有游戏手柄的ID号。
fastgame.utils.joystick.load_all
载入所有游戏手柄。
返回所有游戏手柄对象的列表。
返回类型:List[Joystick]
fastgame.utils.music
Fastgame音频播放工具。
fastgame.utils.music.Player
音频播放器类。
fastgame.utils.music.Player()
用法:
Player(
file: str,
temp_wav: str = 'temp.wav'
)
参数详解:
file
: 音频文件。temp_wav
: 若为MP3类音频文件,则为临时WAV文件路径。
fastgame.utils.music.Player.set_mixer_value
静态方法。
重设混音器参数。
此函数会重启混音器。
用法:
Player.set_mixer_value(
frequency: int = 44100,
size: int = -16,
channels: int = STEREO,
buffer: int = 512
)
参数详解:
frequency
: 播放频率。size
: 每个音频样本使用了多少位。channels
: 是否立体声,1为普通声,2为立体声。buffer
: 音频播放缓冲区大小。缓冲区大小必须是2的幂(如果不是,则向上舍入到下一个最接近的2幂)
fastgame.utils.music.Player.engine
虚拟属性。
Fastgame采用mixer+music的双引擎模式。
实例:
from fastgame import Player
from fastgame.locals import *
player = Player('test.ogg')
engine = player.engine # 获取引擎
player.engine = MUSIC # 设置引擎为pygame.mixer.music
player.engine = MIXER # 设置引擎为pygame.mixer
fastgame.utils.music.Player.play
开始播放音频。
用法:
Player.play(
loops: int = 0,
start: float = 0.0,
fade_ms: int = 0,
max_time: float = 0.0
)
参数详解:
loops
: 第一次播放后将重复多少次,设为-1可无限循环。start
: 引擎为music时,为音乐开始播放的时间位置。fade_ms
: 使声音以0%音量开始播放,并在给定的时间内淡入100%音量。max_time
: 引擎为mixer时,在给定的毫秒数后停止播放。
fastgame.utils.music.Player.pause
暂停所有音乐。
fastgame.utils.music.Player.unpause
继续播放所有音乐,取消暂停。
fastgame.utils.music.Player.stop
停止所有音乐。
fastgame.utils.music.Player.busy
属性值,引擎是否繁忙。
fastgame.utils.music.Player.restart
重新开始所有播放音乐。仅支持music引擎。
fastgame.utils.music.Player.volume
虚拟属性,播放器的音量。
实例:
from fastgame import Player
player = Player('test.ogg')
volume = player.volume # 获取音量
player.volume = 0.75 # 设置音量为75%
fastgame.utils.music.play_sound
播放音频。会在内部创建一个music引擎的fastgame.Player
对象。
用法:
play_sound(
file: str,
**kwargs
)
参数详解:
file
: 音频文件路径。kwargs
: 关键字参数,play的参数
fastgame.utils.printscreen
Fastgame截图工具模块。
fastgame.utils.printscreen.screenshot
对窗口进行截图,并保存。
返回截图图片的fastgame.Sprite
对象。
用法:
screenshot(
save_path: str = 'screenshot.png'
)
参数save_path
: 截图图片路径。
fastgame.utils.timer
Fastgame计时器模块。
fastgame.utils.timer.Timer
Fastgame计时器类。
fastgame.utils.timer.Timer()
创建计时器。
fastgame.utils.timer.Timer.reset
计时器归零。
fastgame.utils.timer.Timer.get
获取计时器计时值的近似值。
用法:
Timer.get(
digits: int = 2
)
参数digits
: 保留的小数点位数。
实例:
import time
from fastgame import Timer
timer = Timer()
timer.reset()
time.sleep(1)
print(timer.get())
fastgame.utils.timer.Timer.get_real
获取计时器计时值的准确值。
fastgame.widget.background
Fastgame背景组件模块。
fastgame.widget.background.Background
Fastgame背景组件类。
继承自fastgame.core.sprite.Sprite
fastgame.widget.background.Background()
用法:
Background(
image: str,
auto_resize=True
)
参数详解:
image
: 背景图片路径。auto_resize
: 是否自适应窗口大小(自动缩放)。
fastgame.widget.background.Background.clone
克隆一个背景,用于双背景。
返回此克隆体。
fastgame.widget.background.Background.rolling_left
向左滚动,需要双背景。
用法:
Background.rolling_left(
speed: int = 4
)
例子:
from fastgame import FastGame, Background
game = FastGame()
background1 = Background('test.png')
background2 = background1.clone()
@game.update
def update():
background1.update()
background2.update()
background1.rolling_left()
background2.rolling_left()
fastgame.widget.background.Background.rolling_right
向右滚动,需要双背景。
用法:
Background.rolling_right(
speed: int = 4
)
fastgame.widget.background.Background.rolling_up
向上滚动,需要双背景。
用法:
Background.rolling_up(
speed: int = 4
)
fastgame.widget.background.Background.rolling_down
向下滚动,需要双背景。
用法:
Background.rolling_up(
speed: int = 4
)
fastgame.widget.button
Fastgame按钮组件模块。
fastgame.widget.button.Button
Fastgame按钮组件类。
fastgame.widget.button.Button()
用法:
Button(
image: str,
size: Tuple[int, int] = None,
command: Callable[[], Any] = _pass,
**kwargs
)
参数详解:
image
: 按钮图片路径。size
: 按钮大小。command
: 当按钮按下时,调用的函数。仿照tkinter
设计模式。callback
: 作为关键字实参被传入时,覆盖command
实参值。
fastgame.widget.button.Button.update
在窗口上更新此按钮,并检测和调用回调。
必须在被Fastgame.update装饰过的函数中调用。
fastgame.widget.button.Button.set_command
设置回调函数。
用法:
Button.set_command(
command: Callable[[], Any]
)
也可做装饰器使用。
实例:
from fastgame import FastGame, Button
game = FastGame()
btn = Button('test.png')
@btn.set_command
def when_btn_down():
...
fastgame.widget.canvas
Fastgame画笔组件和画笔模块。
fastgame.widget.canvas.Canvas
Fastgame画布组件类。
fastgame.widget.canvas.Canvas()
用法:
Canvas(
position: Tuple[int, int] = (0, 0),
size: Tuple[int, int] = (100, 100),
bgcolor: ColorType = BLACK
)
参数详解:
position
: 画笔左上角位置。size
: 画布大小。bgcolor
: 画布背景色。不进行Canvas.update可隐藏画布。
fastgame.widget.canvas.Canvas.update
在窗口上更新此画布。
必须在被Fastgame.update装饰过的函数中调用。
fastgame.widget.canvas.Canvas.init_pen
初始化此画布画笔对象,并获得该画笔对象。
如canvas.init_pen()
等价于Pen(canvas)
。
所有关键字实参均传递给Pen
类。
fastgame.widget.canvas.Pen
Fastgame画笔类。
fastgame.widget.canvas.Pen()
用法:
Pen(
canvas: Canvas,
color: ColorType = WHITE,
start_pos: Tuple[int, int] = (0, 0)
)
参数详解:
canvas
: 画笔的画布实例化对象。color
: 画笔的初始笔触色。start_pos
: 画笔起始位置。
fastgame.widget.canvas.Pen.set_color
设置画笔颜色。
用法:
Pen.set_color(
color: ColorType
)
参数color
: 画笔笔触色。
fastgame.widget.canvas.Pen.down
设置画笔为落笔状态。
抬笔和落笔的状态参考了Scratch3
。
fastgame.widget.canvas.Pen.up
设置画笔为抬笔状态。
fastgame.widget.canvas.Pen.move_to
移动至某点。
当处于落笔状态时,会在原点和移动点画线。
当移动点位于画笔之外时,会引发OutOfCanvasError
用法:
Pen.move_to(
x: int,
y: int
)
参数x
: 移动点X坐标。
参数y
: 移动点Y坐标。
fastgame.widget.canvas.Pen.line
在当前点和另一点之间画线。
另一点不受画布大小影响。
用法:
Pen.line(
x: int,
y: int
)
参数x
: 另一点X坐标。
参数y
: 另一点Y坐标。
fastgame.widget.canvas.Pen.circle
画圆形。
圆形位置不受画布影响。
用法:
Pen.circle(
x: int,
y: int,
radius: int,
fill: bool = True,
width: int = 1
)
x
: 圆形中心X坐标。y
: 圆形中心Y坐标。radius
: 圆形半径。fill
: 是否填充圆形。width
: 圆形边框大小。
fastgame.widget.canvas.Pen.rectangle
画矩形(长方形)。
矩形位置不受画布影响。
用法:
Pen.rectangle(
x: int,
y: int,
size: Tuple[int, int],
fill: bool = True,
width: int = 1
)
参数详解:
x
: 矩形X坐标。y
: 矩形Y坐标。size
: 矩形大小。fill
: 是否填充矩形。width
: 矩形边框大小。
fastgame.widget.canvas.Pen.polygon
绘制任意多边形。
多边形位置不受画布影响。
用法:
Pen.polygon(
points: List[Tuple[int, int]],
fill: bool = True,
width: int = 1
)
参数详解:
points
: 多边形各顶点坐标列表。fill
: 是否填充多边形。width
: 多边形边框大小。
fastgame.widget.canvas.Pen.fill_screen
将窗口统一填充某一种颜色。
用法:
Pen.fill_screen(
fill_color: ColorType
)
参数fill_color
: 填充色。
fastgame.widget.label
Fastgame文字组件模块。
fastgame.widget.label.Label
Fastgame文字组件类。
需要pygame.font
模块运行正常。
有些操作系统不支持。
继承自pygame.sprite.Sprite
。
绝大多数方法与fastgame.core.sprite.Sprite
相同。
fastgame.widget.label.Label()
用法:
Label(
text: str,
font: str = None,
size: int = 16,
use_sys_font: bool = False,
color: ColorType = BLACK,
bgcolor: ColorType = None,
antialias: bool = True,
bold=False,
italic=False,
**kwargs
)
参数详解:
text
: 文本内容。font
: 字体文件路径或字体名称。size
: 文本大小。use_sys_font
: 是否使用系统字体。color
: 文本前景色。bgcolor
: 文本背景色。bold
: 是否加粗。italic
: 是否斜体。
注:粗体和斜体仅在使用系统字体时有效。antialias
: 是否使用抗锯齿。- 关键字实参
fgcolor
: 覆盖color
实参的值。 - 关键字实参
foreground_color
: 覆盖color
实参及fgcolor
关键字实参的值。 - 关键字实参
background_color
: 覆盖bgcolor
实参的值。
fastgame.widget.label.Label.position
虚拟属性。
文字位置。
实例:
from fastgame import FastGame, Label
game = FastGame()
text = Label('Hello, Fast Game')
x, y = text.position # 获取文字位置
text.position = (50, 50) # 设置文字位置
fastgame.widget.label.Label.update
在窗口上更新此文本。
必须在被Fastgame.update装饰过的函数中调用。
fastgame.widget.label.Label.hide
同fastgame.core.sprite.Sprite.hide
。
fastgame.widget.label.Label.show
同fastgame.core.sprite.Sprite.show
。
fastgame.widget.label.Label.collide_other
同fastgame.core.sprite.Sprite.collide_other
。
fastgame.widget.label.Label.collide_edge
同fastgame.core.sprite.Sprite.collide_edge
。
fastgame.widget.label.Label.move_to_mouse
同fastgame.core.sprite.Sprite.move_to_mouse
。
fastgame.widget.label.Label.add_x
同fastgame.core.sprite.Sprite.add_x
。
fastgame.widget.label.Label.add_y
同fastgame.core.sprite.Sprite.add_y
。
fastgame.widget.label.Label.set_x
同fastgame.core.sprite.Sprite.set_x
。
fastgame.widget.label.Label.set_y
同fastgame.core.sprite.Sprite.set_y
。
fastgame.widget.label.Label.move_to
同fastgame.core.sprite.Sprite.move_to
。
fastgame.widget.label.Label.resize
同fastgame.core.sprite.Sprite.resize
。
fastgame.widget.label.Label.set_style
设置字体风格。
用法:
Label.set_style(
color: ColorType = BLACK,
bgcolor: ColorType = None,
antialias: bool = True,
**kwargs
)
所有参数同__init__
方法。
高级实例(设置字体):
from fastgame import FastGame, Label
from pygame.font import SysFont # fastgame兼容pygame
game = FastGame()
text = Label('Hello World')
songti = SysFont('宋体', 16)
text.font = songti
text.set_text(text.text)
fastgame.widget.label.Label.set_text
设置文字。
用法:
Label.set_text(
text: str
)
参数text
: 文本内容。
fastgame.widget.link
Fastgame超链接组件模块。
fastgame.widget.link.LinkButton
Fastgame超链接类,相当于HTML中的<a>
标签。
需要联网。内部封装webbrowser
模块。
继承自fastgame.widget.button.Button
。
如下python代码:
from fastgame import LinkButton
LinkButton('img/test.png', 'https://python.org/')
等价于:
<a href="https://python.org/"><img src="/img/test.png"></a>
fastgame.widget.link.LinkButton()
用法:
LinkButton(
image: str,
url: str,
size: Tuple[int, int] = None,
style=OPEN
)
参数详解:
image
: 按钮图片。url
: 按下按钮所对应的URL。size
: 按钮大小。style
: 浏览器打开方式。
代码 | 打开方式 |
---|---|
fastgame.locals.OPEN | 正常打开 |
fastgame.locals.NEW | 新窗口打开 |
fastgame.locals.NEW_TAB | 新标签页打开 |
fastgame.widget.link.LinkButton.set_url
设置按下按钮所对应的URL。
用法:
LinkButton.set_url(
url: str
)
参数url
: 按下按钮所对应的URL。
fastgame.widget.link.LinkButton.set_style
设置浏览器打开方式。
用法:
LinkButton.set_style(
style=OPEN
)
参数style
: 浏览器打开方式。
fastgame.widget.video.video
Fastgame视频组件模块。
测试功能,可能在之后的版本中删除。
fastgame.widget.video.video.Video
Fastgame视频组件类。
内部使用opencv+numpy+pillow。
加载大视频速度较慢。
视频无声音。但可以使用fastgame.utils.music
播放视频声音。
fastgame.widget.video.video.Video()
用法:
Video(
video_file: str,
position: Tuple[int, int] = (0, 0),
size: Tuple[int, int] = None,
start: int = 0,
set_fps: bool = True,
length: int = 16,
progress_bar: bool = False
)
参数详解:
video_file
: 视频文件路径。position
: 视频左上角相对窗口的位置。size
: 视频缩放后大小。start
: 开始播放时,使用的图片索引。set_fps
: 是否将窗口的FPS设为视频的FPS。length
: 临时图片集名称字符长度。progress_bar
: 是否显示进度条。进度条封装tqdm
。
工作原理:
- 将视频分解为图片集
- 排序并读入各图片
- 按FPS更换图片
fastgame.widget.video.video.Video.update
在窗口上更新此视频组件的这一帧图片。
必须在被Fastgame.update装饰过的函数中调用。
fastgame.widget.video.video.Video.next
将图片调整为下一帧。
若为最后一帧,则重头开始。
返回值:是否为最后一帧图片。
播放实例:
from fastgame import Video, FastGame
game = FastGame()
video = Video('test.mp4', progress_bar=True)
@game.update
def update():
video.update()
video.next()
game.mainloop()
三、Fastgame例子
做一个贪吃蛇
import random
import fastgame
from fastgame.utils.color import * # 导入常用颜色
SNAKE_WIDTH = 20 # 定义贪吃蛇的宽
WIDTH = 850
HEIGHT = 700
game = fastgame.FastGame('Snake', size=(WIDTH, HEIGHT), fps=10) # 创建游戏
canvas = fastgame.Canvas(size=(WIDTH, HEIGHT), bgcolor=WHITE) # 创建贪吃蛇画布
pen = canvas.init_pen() # 创建画笔
score_text = fastgame.Label('Score: 0', size=36, color=BLUE)
snake = [
[WIDTH // 2, HEIGHT // 2 - SNAKE_WIDTH],
[WIDTH // 2, HEIGHT // 2],
[WIDTH // 2, HEIGHT // 2 + SNAKE_WIDTH],
[WIDTH // 2, HEIGHT // 2 + SNAKE_WIDTH * 2]
] # 定义蛇的身体
head = snake[0].copy() # 蛇头
angel = 'left' # 移动方向
score = 0 # 分数
def get_food(): # 定义获取食物的方法
x = random.randint(SNAKE_WIDTH, WIDTH - SNAKE_WIDTH)
y = random.randint(SNAKE_WIDTH, HEIGHT - SNAKE_WIDTH)
x -= x % SNAKE_WIDTH # 防止蛇吃不到食物
y -= y % SNAKE_WIDTH
return [x, y]
def eaten_food(): # 判断是否吃到食物
x0, y0 = food
x1, y1 = head
return abs(x0 - x1) <= SNAKE_WIDTH and abs(y0 - y1) <= SNAKE_WIDTH
def move(move_angel: str = 'left'): # 定义移动方法
global angel, food, score
angel = move_angel
if eaten_food(): # 吃到食物
score += 1
food = get_food()
else:
snake.pop() # 删除蛇的尾巴
if move_angel == 'left':
head[0] -= SNAKE_WIDTH
elif move_angel == 'right':
head[0] += SNAKE_WIDTH
elif move_angel == 'up':
head[1] -= SNAKE_WIDTH
elif move_angel == 'down':
head[1] += SNAKE_WIDTH
snake.insert(0, head.copy()) # 插入蛇头
def dead(): # 判断是否死亡
body = snake.copy()
del body[0]
return (
(head in body) # 撞到自己
or head[0] <= 0 # 撞墙
or head[0] >= WIDTH
or head[1] <= 0
or head[1] >= HEIGHT
)
food = get_food()
@game.update
def update(over=False): # 定义刷新函数
pen.fill_screen(PINK)
score_text.set_text(f'Score: {score}')
score_text.update()
pen.set_color(WHITE) # 蛇身颜色
for body in snake: # 遍历绘制蛇身
pen.rectangle(*body, (SNAKE_WIDTH, SNAKE_WIDTH))
pen.set_color(BLACK) # 蛇头颜色
pen.rectangle(*head, (SNAKE_WIDTH, SNAKE_WIDTH))
pen.set_color(GREEN) # 食物颜色
pen.rectangle(*food, (SNAKE_WIDTH, SNAKE_WIDTH))
move(angel)
if dead(): # Game Over
if not over:
update(True) # 将Game Over那一帧渲染出来
game_over()
def game_over():
over_sprite = fastgame.screenshot()
game_over_text = fastgame.Label('Game Over', size=96, color=WHITE)
game_over_text.position = (0, HEIGHT // 2)
@game.update # 重定义渲染回调
def reset_update():
over_sprite.update()
game_over_text.update()
@game.on_key_down
def on_key_down():
global angel
key = game.event.get('key')
if key == fastgame.K_LEFT and angel != 'right':
angel = 'left'
elif key == fastgame.K_RIGHT and angel != 'left':
angel = 'right'
elif key == fastgame.K_UP and angel != 'down':
angel = 'up'
elif key == fastgame.K_DOWN and angel != 'up':
angel = 'down'
if __name__ == '__main__':
game.mainloop()
做一个跳一跳
素材准备
素材来源:mblock
背景:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UXi5Iggq-1643606273100)(https://res-cn.makeblock.com/mblock/static/assets/scratch/65f2cfe058cbfd2a3b56263759c5c61f.svg)]
角色:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jAEyawVd-1643606273102)(https://res-cn.makeblock.com/mblock/static/assets/scratch/442f1d98da81401ad43560e920765d3f.svg)]
跳板:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JLnDgGSq-1643606273102)(https://res-cn.makeblock.com/mblock/static/assets/scratch/5cceb73efc71c01bfa4a0592ecd6ffcb.svg)]
实现
import fastgame
import random
# 定义长宽
WIDTH = 1000
HEIGHT = 725
SIDE = 150 # 边缘大小
game = fastgame.FastGame('Jump and Jump', (WIDTH, HEIGHT), fps=30)
# 导入素材
background = fastgame.Background('background.svg')
dog = fastgame.Sprite('dog.svg')
drum1 = fastgame.Sprite('drum.svg')
drum2 = drum1.clone()
score_label = fastgame.Label('Score: 0', size=72) # 显示分数的文字组件
timer = fastgame.Timer() # 创建计时器
score = 0
def get_drum_pos(): # 定义获取两个跳板位置的方法
y = HEIGHT // 2
x0 = random.randint(SIDE, WIDTH // 2 - SIDE)
x1 = random.randint(WIDTH // 2 + SIDE, WIDTH - SIDE)
return (x0, y), (x1, y)
def set_pos(): # 重设角色位置
drum1.position, drum2.position = get_drum_pos()
x, y = drum1.position
dog.position = (x, y - 70)
def jump(time): # 跳跃
global score
add = time * 300 # 根据蓄力时间计算跳跃长度
dog.add_x(add)
if not dog.collide_other(drum2): # 没有跳到跳板上
game.destroy()
else:
score += 1
set_pos() # 重设位置
set_pos()
@game.update
def update(): # 定义刷新函数
background.update()
drum1.update()
drum2.update()
score_label.set_text(f'Score: {score}')
score_label.update()
dog.update()
@game.on_key_down
def on_key_down():
if game.event['key'] == fastgame.K_SPACE: # 按下空格键
timer.reset() # 计时器归零
@game.on_key_up
def on_key_up():
if game.event['key'] == fastgame.K_SPACE: # 松开空格键
time = timer.get()
jump(time)
if __name__ == '__main__':
game.mainloop()