- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
[简介]我是 OpenAI 的初学者,我制作了一个自定义游戏,我想在其中实现一个自学习代理。我关注了this guide在 GitHub 上设置存储库,但是我不明白如何格式化我的代码以使用gym-foo/gym_foo/envs/foo_env.py的内容
[问题]是否有人可以指导我如何构建我的代码,使其与以下内容兼容:
class FooEnv(gym.Env):
metadata = {'render.modes': ['human']}
def __init__(self):
...
def step(self, action):
...
def reset(self):
...
def render(self, mode='human', close=False):
...
[代码]
import pygame
import time
import random
from pygame.locals import *
pygame.init()
display_width = 1002
display_height = 720
black = (0,0,0)
white = (255,255,255)
red = (220,0,0)
blue = (53,155,255)
green = (0,190,0)
bright_red = (255,0,0)
bright_green = (0,255,0)
dark_blue = (0,102,204)
yellow = (255, 255, 0)
gameDisplay = pygame.display.set_mode((display_width,display_height)) #creates surface/ display
pygame.display.set_caption('Blob Arena') #name of project
clock = pygame.time.Clock() #sets a clock
#________________________________________________________________________________________
blobImage = pygame.image.load('blob2.png')
blobIcon = pygame.image.load('blob_img.png')
bulletpicture = pygame.image.load("bullet.png")
pygame.display.set_icon(blobIcon)
pause = True
blob_width = 51
blob_height = 51
bullet_width = 12
bullet_height = 5
bullets=[]
bullets2=[]
def blob(x,y):
gameDisplay.blit(blobImage,(x,y)) #drawing to background
def bullets_hit(count):
font = pygame.font.SysFont(None, 25)
text = font.render("Score: "+str(count), True, black)
gameDisplay.blit(text,(0,20))
def player_lives(count):
font = pygame.font.SysFont(None, 25)
text = font.render("Lives Left: "+str(count), True, bright_red)
gameDisplay.blit(text,(0,0))
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(dark_blue)
largeText = pygame.font.Font('freesansbold.ttf', 110)
TextSurf, TextRect = text_objects("Blob Arena", largeText) # Returns text surface and rectangle
TextRect.center = ((display_width / 2), (display_height / 2.5))
gameDisplay.blit(TextSurf, TextRect)
button("Training 1", 200, 430, 140, 53, green, bright_green, game_loop)
button("Training 2", 431, 430, 140, 53, green, bright_green, game_loop)
button("Training 3", 662, 430, 140, 53, green, bright_green, game_loop)
button("Human vs AI", 315.5, 550, 140, 53, green, bright_green, game_loop)
button("Quit", 546.5, 550, 140, 53, red, bright_red, quit_game)
pygame.display.update()
clock.tick(15)
def button(msg,x,y,w,h,ic,ac,action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed() #collects mouse left, right and middle button
if x + w > mouse[0] > x and y + h > mouse[1] > y:
pygame.draw.rect(gameDisplay, ac, (x, y, w, h))
if click[0] == 1 and action!= None:
action()
else:
pygame.draw.rect(gameDisplay, ic, (x, y, w, h))
smallText = pygame.font.Font("freesansbold.ttf", 20)
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ((x + (w / 2)), (y + (h / 2)))
gameDisplay.blit(textSurf, textRect)
def unpause():
global pause
pause = False
def paused():
largeText = pygame.font.Font('freesansbold.ttf', 110)
TextSurf, TextRect = text_objects("Paused", largeText) # Returns text surface and rectangle
TextRect.center = ((display_width / 2), (display_height / 2.5))
gameDisplay.blit(TextSurf, TextRect)
while pause:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
button("Continue", 315.5, 450, 140, 53, green, bright_green, unpause)
button("Quit", 546.5, 450, 140, 53, red, bright_red, quit_game)
pygame.display.update()
clock.tick(15)
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def quit_game():
pygame.quit()
quit()
def game_over():
largeText = pygame.font.Font('freesansbold.ttf', 110)
TextSurf, TextRect = text_objects("Game Over", largeText) # Returns text surface and rectangle
TextRect.center = ((display_width / 2), (display_height / 2.5))
gameDisplay.blit(TextSurf, TextRect)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
button("Play Again", 280.5, 450, 140, 53, green, bright_green,game_loop)
button("Quit", 581.5, 450, 140, 53, red, bright_red,quit_game)
pygame.display.update()
clock.tick(15)
def game_loop():
global pause
x = (display_width * 0.08)
y = (display_height * 0.2)
x_change = 0
y_change = 0
blob_speed = 2
velocity = [2, 2]
score = 0
lives = 3
pos_x = display_width/1.2
pos_y = display_height/1.2
previous_time = pygame.time.get_ticks()
previous_time2 = pygame.time.get_ticks()
gameExit = False
while not gameExit:
for event in pygame.event.get():#monitors hardware movement/ clicks
if event.type == pygame.QUIT:
pygame.quit()
quit()
pos_x += velocity[0]
pos_y += velocity[1]
if pos_x + blob_width > display_width or pos_x < 601:
velocity[0] = -velocity[0]
if pos_y + blob_height > display_height or pos_y < 0:
velocity[1] = -velocity[1]
for b in range(len(bullets2)):
bullets2[b][0] -= 6
for bullet in bullets2:
if bullet[0] < 0:
bullets2.remove(bullet)
current_time2 = pygame.time.get_ticks()
#ready to fire when 500 ms have passed.
if current_time2 - previous_time2 > 500:
previous_time2 = current_time2
bullets2.append([pos_x+25, pos_y+24])
# Checks to see if any keys are held down and remembers them with the variable keys.
keys = pygame.key.get_pressed()
for b in range(len(bullets)):
bullets[b][0] += 6
for bullet in bullets:
if bullet[0] > 1005:
bullets.remove(bullet)
if keys[pygame.K_SPACE]:
current_time = pygame.time.get_ticks()
#ready to fire when 500 ms have passed.
if current_time - previous_time > 500:
previous_time = current_time
bullets.append([x+25, y+24])
# If the player is holding down one key or the other the blob moves in that direction
if x < 0:
x = 0
if keys[pygame.K_a]:
x_change = -blob_speed
if x > 401 - blob_width:
x = 401 - blob_width
if keys[pygame.K_d]:
x_change = blob_speed
if keys[pygame.K_p]:
pause = True
paused()
# If the player is holding down both or neither of the keys the blob stops
if keys[pygame.K_a] and keys[pygame.K_d]:
x_change = 0
if not keys[pygame.K_a] and not keys[pygame.K_d]:
x_change = 0
if y < 0:
y = 0
if keys[pygame.K_w]:
y_change = -blob_speed
if y > display_height - blob_height:
y = display_height - blob_height
if keys[pygame.K_s]:
y_change = blob_speed
if keys[pygame.K_w] and keys[pygame.K_s]:
y_change = 0
if not keys[pygame.K_w] and not keys[pygame.K_s]:
y_change = 0
#print(event)
# Reset x and y to new position
x += x_change
y += y_change
gameDisplay.fill(blue) #changes background surface
bullets_hit(score)
player_lives(lives)
pygame.draw.line(gameDisplay, black, (601, display_height), (601, 0), 3)
pygame.draw.line(gameDisplay, black, (401, display_height), (401, 0), 3)
blob(pos_x, pos_y)
blob(x, y)
for bullet in bullets:
gameDisplay.blit(bulletpicture, pygame.Rect(bullet[0], bullet[1], 0, 0))
if bullet[0] > pos_x and bullet[0] < pos_x + blob_width:
if bullet[1] > pos_y and bullet[1] < pos_y + blob_height or bullet[1] + bullet_height > pos_y and bullet[1] + bullet_height < pos_y + blob_height:
bullets.remove(bullet)
score+=1
for bullet in bullets2:
gameDisplay.blit(bulletpicture, pygame.Rect(bullet[0], bullet[1], 0, 0))
if bullet[0] + bullet_width < x + blob_width and bullet[0] > x:
if bullet[1] > y and bullet[1] < y + blob_height or bullet[1] + bullet_height > y and bullet[1] + bullet_height < y + blob_height:
bullets2.remove(bullet)
lives-=1
if lives == 0:
game_over()
pygame.display.update() #update screen
clock.tick(120)#moves frame on (fps in parameters)
game_intro()
game_loop()
pygame.quit()
quit()
[其他信息]我将使用 https://github.com/Hvass-Labs/TensorFlow-Tutorials/blob/master/reinforcement_learning.py 中的强化学习算法据我了解,需要有一个gym环境才能让gym.make()工作。任何帮助将不胜感激,如果需要更多信息,请告诉我。
最佳答案
我没有使用 pygame
库的经验,也不了解其内部工作原理,这可能会对哪些代码需要在哪里运行产生一些影响,所以我不能 100% 确定所有那。但是,最好从一些直观的理解开始,大致了解应该在哪里发生的事情:
__init__()
应该运行任何一次性设置。我可以想象像 pygame.init()
这样的东西可能必须放在这里,但我不能 100% 确定,因为我不熟悉 pygame
。 step()
,然后运行游戏的单个“帧”,根据代理选择的 Action 将其向前移动。或者,如果您的游戏中单个 Action 需要多个帧,则应在此处运行多个帧。本质上:让游戏继续前进,直到到达代理应该再次选择新 Action 的点,然后返回当前的游戏状态。reset()
应该...好吧,重置游戏。因此,恢复到(或随机的,无论你想要什么)初始游戏状态,运行可能需要的任何清理。例如,我也可以想象 pygame.init() 属于这里。这取决于该函数到底做什么。如果只需要运行一次,则属于__init__()
。如果它需要在每个新游戏/“剧集”开始时运行,则 ir 属于 reset()
。render()
可能应该包含大部分与图形相关的代码。例如,您可以尝试从 cartpole environment 中获取灵感。在gym中,这里也绘制了一些相当简单的图形。看起来它应该恰好绘制一帧。现在,看看您开始的代码,似乎有大量的用户界面代码...与按钮、暂停/取消暂停、花哨的(动画?)介绍相关的各种代码比赛开始。不知道你是否有能力摆脱这一切?如果您纯粹进行强化学习,那么您可能可以。如果您仍然需要用户交互,则可能不能,然后事情就会变得更加困难,因为所有这些事情都不能很好地适应 gym
框架。
我可以尝试对代码的剩余部分及其应该去的位置进行一些有根据的猜测,但无论如何,您都应该根据上面更一般的准则仔细检查所有内容:
def reset(self):
# all the following code seems to define the initial game state
x = (display_width * 0.08)
y = (display_height * 0.2)
x_change = 0
y_change = 0
blob_speed = 2
velocity = [2, 2]
score = 0
lives = 3
pos_x = display_width/1.2
pos_y = display_height/1.2
bullets=[]
bullets2=[]
step()
可能应该包含 game_loop()
中 while
循环中的大部分代码。不过,应该修改按键输入检查代码,而是应该开始使用传递到 step()
中的 action
。最后,step()
预计返回一个包含以下内容的元组:
True
如果游戏现在结束,False
否则。{}
。关于python - OpenAI 将自定义游戏集成到健身房环境中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49637378/
我需要将文本放在 中在一个 Div 中,在另一个 Div 中,在另一个 Div 中。所以这是它的样子: #document Change PIN
奇怪的事情发生了。 我有一个基本的 html 代码。 html,头部, body 。(因为我收到了一些反对票,这里是完整的代码) 这是我的CSS: html { backgroun
我正在尝试将 Assets 中的一组图像加载到 UICollectionview 中存在的 ImageView 中,但每当我运行应用程序时它都会显示错误。而且也没有显示图像。 我在ViewDidLoa
我需要根据带参数的 perl 脚本的输出更改一些环境变量。在 tcsh 中,我可以使用别名命令来评估 perl 脚本的输出。 tcsh: alias setsdk 'eval `/localhome/
我使用 Windows 身份验证创建了一个新的 Blazor(服务器端)应用程序,并使用 IIS Express 运行它。它将显示一条消息“Hello Domain\User!”来自右上方的以下 Ra
这是我的方法 void login(Event event);我想知道 Kotlin 中应该如何 最佳答案 在 Kotlin 中通配符运算符是 * 。它指示编译器它是未知的,但一旦知道,就不会有其他类
看下面的代码 for story in book if story.title.length < 140 - var story
我正在尝试用 C 语言学习字符串处理。我写了一个程序,它存储了一些音乐轨道,并帮助用户检查他/她想到的歌曲是否存在于存储的轨道中。这是通过要求用户输入一串字符来完成的。然后程序使用 strstr()
我正在学习 sscanf 并遇到如下格式字符串: sscanf("%[^:]:%[^*=]%*[*=]%n",a,b,&c); 我理解 %[^:] 部分意味着扫描直到遇到 ':' 并将其分配给 a。:
def char_check(x,y): if (str(x) in y or x.find(y) > -1) or (str(y) in x or y.find(x) > -1):
我有一种情况,我想将文本文件中的现有行包含到一个新 block 中。 line 1 line 2 line in block line 3 line 4 应该变成 line 1 line 2 line
我有一个新项目,我正在尝试设置 Django 调试工具栏。首先,我尝试了快速设置,它只涉及将 'debug_toolbar' 添加到我的已安装应用程序列表中。有了这个,当我转到我的根 URL 时,调试
在 Matlab 中,如果我有一个函数 f,例如签名是 f(a,b,c),我可以创建一个只有一个变量 b 的函数,它将使用固定的 a=a1 和 c=c1 调用 f: g = @(b) f(a1, b,
我不明白为什么 ForEach 中的元素之间有多余的垂直间距在 VStack 里面在 ScrollView 里面使用 GeometryReader 时渲染自定义水平分隔线。 Scrol
我想知道,是否有关于何时使用 session 和 cookie 的指南或最佳实践? 什么应该和什么不应该存储在其中?谢谢! 最佳答案 这些文档很好地了解了 session cookie 的安全问题以及
我在 scipy/numpy 中有一个 Nx3 矩阵,我想用它制作一个 3 维条形图,其中 X 轴和 Y 轴由矩阵的第一列和第二列的值、高度确定每个条形的 是矩阵中的第三列,条形的数量由 N 确定。
假设我用两种不同的方式初始化信号量 sem_init(&randomsem,0,1) sem_init(&randomsem,0,0) 现在, sem_wait(&randomsem) 在这两种情况下
我怀疑该值如何存储在“WORD”中,因为 PStr 包含实际输出。? 既然Pstr中存储的是小写到大写的字母,那么在printf中如何将其给出为“WORD”。有人可以吗?解释一下? #include
我有一个 3x3 数组: var my_array = [[0,1,2], [3,4,5], [6,7,8]]; 并想获得它的第一个 2
我意识到您可以使用如下方式轻松检查焦点: var hasFocus = true; $(window).blur(function(){ hasFocus = false; }); $(win
我是一名优秀的程序员,十分优秀!