在过去一周中,我一直在制作神经网络来玩流行的Pong游戏。我已经用keras制作了神经网络,尽管它可以运行并且可以运行,但是我不知道如何设置它以实际玩Pygame制作的Pong游戏。
以下是相关代码:
model = load_model('first_model_simplify_16.h5')
#scaler
scaler = MinMaxScaler(feature_range=(0,1))
#mean scaler
def normalize(a):
mean = np.mean(a)
stddev = np.std(a)
sA = [(x-mean)/stddev for x in a]
return sA
# game loop
while True:
draw(window)
#loop that inserts the paddle and ball position in their place in the list
# create array to save all the features
a = np.array([ball_pos[0], ball_pos[1], paddle1_pos[1]])
sA = np.array(normalize(a)).reshape(1,-1)
prediction = model.predict_classes(sA)
print(prediction)
for event in pygame.event.get():
if event.type == KEYDOWN:
keydown(event)
if event.key == K_w :
X.append([ball_pos[0], ball_pos[1], paddle1_pos[1], ball_pos[1] - paddle1_pos[1]])
elif event.key == K_s :
X.append([ball_pos[0], ball_pos[1], paddle1_pos[1], ball_pos[1] - paddle1_pos[1]])
elif event.type == KEYUP:
keyup(event)
elif event.type == QUIT:
pygame.quit()
sys.exit()
#TESTING
pygame.display.update()
fps.tick(60)
该模型正在做出预测(尽管不是很好),但我不知道如何使用这些预测来使桨向上或向下移动。
如何使用模型的预测更改pygame中的事件?
编辑:这是模型的输出
C:\Users\berro\Anaconda3.6\python.exe
C:/Users/berro/PycharmProjects/SecondPongGame/testPong.py
C:\Users\berro\Anaconda3.6\lib\site-packages\h5py\__init__.py:36:
FutureWarning: Conversion of the second argument of issubdtype from `float`
to `np.floating` is deprecated. In future, it will be treated as `np.float64
== np.dtype(float).type`.
from ._conv import register_converters as _register_converters
Using TensorFlow backend.
2018-07-14 13:17:54.652176: I
T:\src\github\tensorflow\tensorflow\core\platform\cpu_feature_guard.cc:140]
Your CPU supports instructions that this TensorFlow binary was not compiled
to use: AVX2
[1]
[1]
[1]
[1]
[1]
[1]
,它将继续输出每个单帧。 有时根据输入也为0。
答案 0 :(得分:1)
我不知道keras是如何工作的,但是如果您想在条件为真的情况下将事件添加到pygame的事件队列中,则可以使用pygame.event.post
函数。
首先,您必须创建一个pygame.event.Event
实例,该实例将传递给pygame.event.post
。您需要传递事件类型作为第一个参数,例如pygame.KEYDOWN
或pygame.MOUSEBUTTONDOWN
,以及用于定义事件特定值的字典或关键字args,例如key
,{{ 1}}和unicode
属性。 (scancode
和MOUSEBUTTONDOWN
事件仅具有MOUSEBUTTONUP
和pos
属性。)
在此示例中,每60帧将button
事件添加到队列中。
pygame.KEYDOWN
编辑:由于您只想根据预测值向上或向下移动桨板,因此您只需将桨板的速度设置为相应的值即可:
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
BG_COLOR = pygame.Color('gray12')
frame_count = 0
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
print(event)
if event.key == pygame.K_w:
print('w key pressed')
frame_count += 1
if frame_count >= 60:
frame_count = 0
# Either pass a dictionary ...
# event = pygame.event.Event(pygame.KEYDOWN, {'key': pygame.K_w, 'unicode': 'w', etc.})
# or pass keyword arguments.
event = pygame.event.Event(pygame.KEYDOWN, key=pygame.K_w, unicode='w', scancode=17, mod=0)
# Add the event to pygame's event queue.
pygame.event.post(event)
screen.fill(BG_COLOR)
pygame.display.flip()
clock.tick(60)
pygame.quit()