今天我们学习一个新的库,叫做arcade
目录
【下载arcade】
【用pip下载】(推荐)
用win+R()调出命令窗口,Windows输入:
pip install arcade
其它系统输入:
pip3 install arcade
【PyPi下载】(不推荐)
在PyPi搜索arcade找到arcade 2.5.7(课程版本),选择Download files下载。
【创建窗体】
【过程+函数创建】
from arcade import*
WIDTH,HEIGHT = (800,600) # 窗体宽高
TITLE = "示例窗口" # 窗体标题
open_window(WIDTH,HEIGHT,TITLE)
run() # 运行窗口
【过程+类创建】
from arcade import*
WIDTH,HEIGHT = (800,600) # 窗体宽高
TITLE = "示例窗口" # 窗体标题
game = Window(WIDTH,HEIGHT,TITLE) # 部分电脑为arcade.Window(WIDTH,HEIGHT,TITLE)
run() # 运行窗口
【面向对象】
from arcade import*
WIDTH,HEIGHT = (800,600) # 窗体宽高
TITLE = "示例窗口" # 窗体标题
class MyGame(Window): # 部分电脑为arcade.Window
def __init__(self,width,height,title):
super().__init__(width,height,title)
def on_draw(self):
start_render()
def on_update(self,delta_time):
pass
if __name__ == "__main__":
game = MyGame(WIDTH,HEIGHT,TITLE)
run() # 运行窗口
【开始编写】
现在,我们最原始的代码“Hello World”写上去吧
draw_text方法
draw_text(text,start_x,start_y,color,font_size,font_name)
text:文本内容
start_x,start_y:第一个字起始的xy坐标
color:字体颜色
font_size:字体大小(有默认值)
font_name:使用字体名称(有默认值)
现在,在on_draw添加这行代码(示例只显示整个on_draw代码)
def on_draw(self):
start_render()
draw_text("Hello World!",400,300,(255,0,0),32)
结果如下:
【炫酷的HelloWorld】
我们来扩展一下,如何有一个炫酷的Hello World
首先我们先创建一个colors属性,储存各种颜色;color_index属性储存索引(只展示__init__方法)
def __init__(self, width, height, title):
super().__init__(width, height, title)
self.colors = [(255,0,0),(255,245,0),(245,255,0),(0,255,0),(0,255,245),(0,245,255),(0,0,255)]
self.color_index = 0
接着我们定义一个on_update方法,除了self以外,还有一个参数delta_time
on_draw和on_update每过1÷60秒都会执行一次,我们可以利用这个来做出动态效果
这时,我们要在on_update中增加索引,为了不让变化过快,我们使用小数(只展示on_update)
def on_update(self, delta_time):
self.color_index += 0.2
然后要在on_draw中编辑索引,为了防止索引错误(IndexError)我们用%取余
on_draw代码如下
def on_draw(self):
start_render()
draw_text("HelloWorld!",400,300,self.colors[int(self.color_index)%len(self.colors)],32)
现在我们来给字加上边框
draw_rectangle_outline
draw_rectangle_outline(center_x,center_y,width,height,color,border_width,tilt_angle)
center_x,center_y: 矩形中心xy坐标
width,height: 矩形宽高
color: 矩形颜色
border_width: 边框长度
tilt_angle: 矩形倾角
现在我们来实战一下(只展示on_draw)
def on_draw(self):
start_render()
color = self.colors[int(self.color_index)%len(self.colors)]
draw_text("Hello World!",400,300,color,32)
draw_rectangle_outline(495,326,24*len("HelloWorld"),39,color,3)
效果如下:
【完整代码】
教程结束,展示完整代码吧
from arcade import *
WIDTH, HEIGHT = (800, 600) # 窗体宽高
TITLE = "示例窗口" # 窗体标题
class MyGame(Window): # 部分电脑为arcade.Window
def __init__(self, width, height, title):
super().__init__(width, height, title)
self.colors = [(255,0,0),(255,245,0),(245,255,0),(0,255,0),(0,255,245),(0,245,255),(0,0,255)]
self.color_index = 0
def on_draw(self):
start_render()
color = self.colors[int(self.color_index)%len(self.colors)]
draw_text("Hello World!",400,300,color,32)
draw_rectangle_outline(495,326,24*len("HelloWorld"),39,color,3)
def on_update(self, delta_time):
self.color_index += 0.2
if __name__ == "__main__":
game = MyGame(WIDTH, HEIGHT, TITLE)
run() # 运行窗口