-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.py
242 lines (197 loc) · 8.17 KB
/
game.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
import math
import os
import re
from typing import Tuple
import numpy
from imgs.bird import DEFAULT_BIRD_HEIGHT, DEFAULT_BIRD_WIDTH
from imgs.pipe import PIPE_HAT_HEIGHT
import random
import time
from objects.ground import GROUND_HEIGHT
from prng import PRNG
BIRD_LEFT_POSITION = 0.2
# BIRD_RIGHT_POSITION = 0.5
BIRD_RIGHT_POSITION = 0.2
BIRD_SPEED = 3
BIRD_CLICK_SPEED = -5
WORLD_GRAVITY = 0.4
GAME_STATE_INIT = 0
GAME_STATE_RUNNING = 1
GAME_STATE_END = 2
PIPE_WIDTH = 60
PIPE_SPACING = 120
PIPE_SAFE_MARGIN = (PIPE_WIDTH + PIPE_SPACING)
PIPE_INTERVAL_MIN_HEIGHT = 70
# less means harder
GAME_DIFFICULT = 1.8
class AbstractPipe:
g_id = 0
def __init__(self, x: int, interval_y: int, interval_height: int, window_height: int) -> None:
self.id = AbstractPipe.g_id
AbstractPipe.g_id += 1
self.width = PIPE_WIDTH
self.x = x
self.interval_y = interval_y
self.interval_height = interval_height
self.window_height = window_height
@property
def upperPosition(self):
return (self.x, 0)
@property
def upperSize(self):
return (self.width, self.interval_y)
@property
def lowerPosition(self):
return (self.x, self.interval_y + self.interval_height)
@property
def lowerSize(self):
return (self.width, self.window_height - self.lowerPosition[1])
@property
def right(self):
return self.x + self.width
@property
def xmid(self):
return self.x + self.width // 2
@property
def ymid(self):
return self.interval_y + self.interval_height // 2
def hit(self, y: int):
if y < self.interval_y or y >= self.interval_y + self.interval_height:
return True
return False
def getRandomSeed():
return ''.join(random.sample('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', 16))
class Game:
def __init__(self, window_size: Tuple[int], replay_flag: bool = False) -> None:
self.window_size = window_size
self.bird_xrange = [int(BIRD_LEFT_POSITION * window_size[0]), int(BIRD_RIGHT_POSITION * window_size[0])]
self.score = 0
self.best_score = 0
self.operations = []
self.prng = PRNG()
self.replay_flag = replay_flag
self.reset()
def fitCamera(self):
if self.bird_world_position[0] < self.camera_rect[0] + self.bird_xrange[0]:
self.camera_rect[0] = self.bird_world_position[0] - self.bird_xrange[0]
elif self.bird_world_position[0] > self.camera_rect[0] + self.bird_xrange[1]:
self.camera_rect[0] = self.bird_world_position[0] - self.bird_xrange[1]
def update(self):
if self.status == GAME_STATE_RUNNING:
for i in range(2):
self.bird_world_position[i] += self.bird_speed[i]
self.bird_speed[1] += WORLD_GRAVITY
self.bird_rotate = math.atan2(self.bird_speed[1], self.bird_speed[0] * 2) # less rotate angle
passed_pipes = [p for p in self.pipes if p.xmid <= self.bird_world_xmid]
if len(passed_pipes) > 0:
self.score = passed_pipes[-1].id + 1
if self.score > self.best_score:
self.best_score = self.score
if self.checkCollision():
self.status = GAME_STATE_END
if len(self.operations) > 0:
self.saveOperations()
self.operations.append(0)
self.updatePipe()
self.fitCamera()
def reset(self, seed = getRandomSeed()):
AbstractPipe.g_id = 0
self.seed = seed
self.prng.seed(self.seed)
self.status = GAME_STATE_INIT
self.operations = []
self.score = 0
self.bird_rotate = 0
self.bird_speed = [BIRD_SPEED, 0]
self.bird_world_position = [0, self.window_size[1] // 2]
self.camera_rect = [0, 0, self.window_size[0], self.window_size[1]]
self.pipes = [self.makeRandomPipe(self.bird_world_position[0] + PIPE_SAFE_MARGIN, self.window_size[1] - GROUND_HEIGHT, PIPE_INTERVAL_MIN_HEIGHT * GAME_DIFFICULT)]
self.fitCamera()
def updatePipe(self):
l, r = self.camera_rect[0] - PIPE_SAFE_MARGIN, self.camera_rect[0] + self.camera_rect[2] + PIPE_SAFE_MARGIN
self.pipes = [p for p in self.pipes if p.x >= l]
last = self.pipes[-1]
while last.x + (PIPE_WIDTH + PIPE_SPACING) < r:
pipe = (self.makeRandomPipe(last.x + (PIPE_SPACING + PIPE_WIDTH), self.window_size[1] - GROUND_HEIGHT, PIPE_INTERVAL_MIN_HEIGHT * GAME_DIFFICULT))
self.pipes.append(pipe)
last = self.pipes[-1]
def makeRandomPipe(self, x: int, full_height: int, expect_interval_height: int):
h = int(self.prng.random(0.8, 1.2) * expect_interval_height)
k = int(math.floor(self.prng.random(PIPE_HAT_HEIGHT, full_height - h - PIPE_HAT_HEIGHT)))
return AbstractPipe(x, k, h, self.window_size[1])
@property
def next_pipe(self):
return [p for p in self.pipes if p.xmid > self.bird_world_xmid][0]
@property
def bird_position(self):
return (self.bird_world_position[0] - self.camera_rect[0], self.bird_world_position[1] - self.camera_rect[1])
@property
def bird_world_xmid(self):
return self.bird_world_position[0] + DEFAULT_BIRD_WIDTH // 2
def checkCollision(self):
bird_l, bird_r = self.bird_world_position[0], self.bird_world_position[0] + DEFAULT_BIRD_WIDTH
bird_t, bird_b = self.bird_world_position[1], self.bird_world_position[1] + DEFAULT_BIRD_HEIGHT
if bird_t <= 0 or bird_b >= self.window_size[1] - GROUND_HEIGHT:
return True
for p in self.pipes:
if bird_r in range(p.x, p.right) or bird_l in range(p.x, p.right):
if p.hit(bird_t) or p.hit(bird_b):
return True
return False
def action_fly(self):
if self.bird_speed[1] * BIRD_CLICK_SPEED < 0:
self.bird_speed[1] = 0
self.bird_speed[1] += BIRD_CLICK_SPEED
self.operations[-1] += 1
def click(self):
if self.status == GAME_STATE_RUNNING:
self.action_fly()
if self.status == GAME_STATE_INIT:
self.start()
if self.status == GAME_STATE_END:
self.reset()
self.status = GAME_STATE_INIT
@property
def ready(self):
return self.status == GAME_STATE_INIT
@property
def running(self):
return self.status == GAME_STATE_RUNNING
@property
def dead(self):
return self.status == GAME_STATE_END
def start(self):
assert(self.status == GAME_STATE_INIT)
self.status = GAME_STATE_RUNNING
def saveOperations(self):
timestr = time.strftime(f'%Y_%m_%d_%H_%M_%S__score__{self.score}', time.localtime())
filename = f'{timestr}.log'
dirpath = os.path.join('log', 'actions')
if not os.path.exists(dirpath) or not os.path.isdir(dirpath):
if not os.path.exists('log') or not os.path.isdir('log'):
os.mkdir('log')
os.mkdir(dirpath)
if not self.replay_flag:
with open(os.path.join(dirpath, filename), 'w') as f:
print(self.seed, file=f)
print(self.operations, file=f)
else:
print(self.operations)
with open(os.path.join('log', 'scores.txt'), 'a') as f:
print(timestr, file=f)
print(f'{self.seed} ({self.bird_world_xmid:.3f}, {self.bird_world_position[1]:.3f}) to ({self.next_pipe.x:.3f}, {self.next_pipe.ymid:.3f})', file=f)
print(f'reward {self.reward:.3f} = {self.reward_x:.3f} + {self.score:.3f} + {self.reward_y:.3f}', file=f)
# print([p.x for p in self.pipes], file=f)
@property
def bird_y_diff_to_next_pipe(self):
return abs(self.bird_world_position[1] - self.next_pipe.ymid)
@property
def reward_x(self):
r1 = ((self.bird_world_position[0] % 180) / 180)
return self.bird_world_position[0] // 180 + r1 * r1 * r1
@property
def reward_y(self):
return -2 * (self.bird_y_diff_to_next_pipe / self.window_size[1])
@property
def reward(self):
return self.reward_x + self.score + self.reward_y