-
Notifications
You must be signed in to change notification settings - Fork 0
/
human_train.py
101 lines (80 loc) · 2.59 KB
/
human_train.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import pygame
import matplotlib.pyplot as plt
import numpy as np
import torch
from tetris.game import TetrisGame
from tetris.agent import TetrisAgent
import rl.training as T
from rl.replay_buffer import ReplayBuffer
tetris = TetrisGame(width=12, height=26)
agent = TetrisAgent(ncols=12, nrows=26, nactions=4, epsilon=0.3)
agent.load_state_dict(torch.load('tetris.pkl'))
exp_replay = ReplayBuffer(size=1000)
lr = 1e-4
batch_size = 16
opt = torch.optim.Adam(agent.parameters(), lr=lr)
pygame.init()
cell_size = 30
width, height = tetris.width*cell_size, tetris.height*cell_size
win = pygame.display.set_mode((width, height))
pygame.display.set_caption('Tetris')
colors = [
(0, 0, 0),
(255, 255, 255),
(255, 10, 10),
(10, 255, 10),
(10, 10, 255),
(255, 255, 10),
(10, 255, 255),
(255, 10, 255)
]
black = colors[0]
white = colors[1]
clock = pygame.time.Clock()
prev_state = tetris.reset()
points = 0
running = True
paused = False
human_playing = True
while running:
clock.tick(10)
action = 'nothing'
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
if event.key == pygame.K_UP:
action = 'up'
if event.key == pygame.K_LEFT:
action = 'left'
if event.key == pygame.K_RIGHT:
action = 'right'
if event.key == pygame.K_SPACE: # space ставит игру на паузу
paused = not paused
if event.key == pygame.K_RETURN: # при нажатии enter меняем игрока(человек или нейронка)
human_playing = not human_playing
if event.type == pygame.QUIT:
running = False
if paused:
continue
if human_playing:
action = TetrisGame.action_names[action]
else:
qvalues = agent.get_qvalues(prev_state[np.newaxis])
action = agent.sample_actions(qvalues)[0]
state, reward, terminated, _ = tetris.step(action) # (ignore truncated flag)
points += reward
if terminated:
print(f'You scored {points} points!')
state = tetris.reset()
paused = True
exp_replay.add(prev_state, action, reward, state, done=terminated)
prev_state = state
grid = state[1]
win.fill(black)
for i in range(grid.shape[0]):
for j in range(grid.shape[1]):
if grid[i, j] != 0:
pygame.draw.rect(win, colors[grid[i, j]-1], (j*cell_size, i*cell_size, cell_size, cell_size))
pygame.display.flip()
pygame.quit()