强化学习实战 | 自定义gym环境之显示字符串
时间:2022-01-09 作者:wsy950409
如果想用强化学习去实现扫雷、2048这种带有数字提示信息的游戏,自然是希望自定义 gym 环境时能把字符显示出来。上网查了很久,没有找到gym自带的图形工具Viewer可以显示字符串的信息,反而是通过pyglet:
import pyglet from 域名sic_control import rendering class DrawText: def __init__(self, label:域名l): 域名l=label def render(self): 域名() screen_width = 500 screen_height = 500 viewer = 域名er(screen_width, screen_height + 20) text = \'hello world\' label = 域名l(text, font_size=36, x=100, y=250, anchor_x=\'left\', anchor_y=\'bottom\', color=(255, 123, 255, 255)) 域名() 域名geom(DrawText(label)) 域名er(return_rgb_array=False)
其中,lable的坐标x y是以左下两边为x y轴(而Viewer是以左上边为轴,这意味着显示图案和文字还得用两套坐标系...),anchor_x 和 anchor_y 指的是label对象的锚点,即如何将label对象视为一个点,有top / bottom / center / baseline四种选择。
效果:
再配合 Python动态变量名定义与调用 的方法,就可以批量地显示字符串了:
import pyglet from 域名sic_control import rendering class DrawText: def __init__(self, label:域名l): 域名l=label def render(self): 域名() screen_width = 500 screen_height = 500 viewer = 域名er(screen_width, screen_height) for i in range(10): for j in range(10): exec(\'label_{}_{} = {}\'.format(i, j, None)) names = locals() names[\'label_\' + str(i) + \'_\' + str(j)] = 域名l(\'{}\'.format(j), font_size=15, x=i*50+25, y=j*50+25, anchor_x=\'left\', anchor_y=\'bottom\', color=(i*10, i*20, i*25, 255)) label = names[\'label_{}_{}\'.format(i, j)] 域名() 域名geom(DrawText(label)) 域名er(return_rgb_array=False)
效果: