Skip to main content
 首页 » 编程设计

python之如何根据神经网络预测改变pygame中的事件

2024年12月31日9insus

在过去的一周里,我一直在制作一个神经网络来玩热门游戏 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,具体取决于输入。

请您参考如下方法:

我不知道 keras 是如何工作的,但是如果你想在条件为真时将事件添加到 pygame 的事件队列,你可以使用 pygame.event.post功能。

首先你必须创建一个 pygame.event.Event将传递给 pygame.event.post 的实例。您需要将事件类型作为第一个参数传递,例如 pygame.KEYDOWN 或 pygame.MOUSEBUTTONDOWN,以及定义事件特定值的字典或关键字参数像 key、unicode 和 scancode 属性。 (MOUSEBUTTONDOWN 和 MOUSEBUTTONUP 事件只有一个 pos 和一个 button 属性。)

这是一个示例,其中每 60 帧将一个 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() 

编辑:由于您只想根据预测值向上或向下移动桨,您可以简单地将桨的速度设置为相应的值:

if prediction == [0]: 
    paddle_speed = -5 
elif prediction == [1]: 
    paddle_speed = 5 
 
paddle_pos_y += paddle_speed