feat: 新增 RL Enviroment
This commit is contained in:
parent
52bf416675
commit
6cfd08095e
61
enviroment.py
Normal file
61
enviroment.py
Normal file
@ -0,0 +1,61 @@
|
||||
from game import TetrisGame
|
||||
|
||||
class TetrisEnviroment():
|
||||
def __init__(self) -> None:
|
||||
self.game = TetrisGame()
|
||||
self.score = 0
|
||||
|
||||
def step(self, mode):
|
||||
if mode == 0: # 不動
|
||||
None
|
||||
elif mode == 1: # left 1
|
||||
self.game.action('l')
|
||||
elif mode == 2: # left 2
|
||||
for i in range(2):
|
||||
self.game.action('l')
|
||||
elif mode == 3: # left 3
|
||||
for i in range(3):
|
||||
self.game.action('l')
|
||||
elif mode == 4: # right 1
|
||||
self.game.action('r')
|
||||
elif mode == 5: # right 2
|
||||
for i in range(2):
|
||||
self.game.action('r')
|
||||
elif mode == 6: # right 3
|
||||
for i in range(3):
|
||||
self.game.action('r')
|
||||
elif mode == 7: # rotate 1
|
||||
self.game.action('f')
|
||||
elif mode == 8: # rotate 2
|
||||
for i in range(2):
|
||||
self.game.action('f')
|
||||
elif mode == 9: # rotate 3
|
||||
for i in range(3):
|
||||
self.game.action('f')
|
||||
self.game.action('d')
|
||||
|
||||
deltaScore = self.game.score - self.score
|
||||
self.score = self.game.score
|
||||
|
||||
return self.game.view(), deltaScore, self.game.done, (self.game.block.x, self.game.block.block.y)
|
||||
# observation, reward, done, info(block location)
|
||||
|
||||
def observation(self):
|
||||
return self.game.view()
|
||||
|
||||
env = TetrisEnviroment()
|
||||
while 1:
|
||||
views = env.observation()
|
||||
for i in range(20):
|
||||
print(str(i).rjust(2), end=' ')
|
||||
for j in range(10):
|
||||
if views[i][j]:
|
||||
print('■', end='')
|
||||
else:
|
||||
print('□', end='')
|
||||
print()
|
||||
action = int(input("Action: "))
|
||||
observation, reward, done = env.step(action)
|
||||
print(observation, reward, done)
|
||||
if done:
|
||||
break
|
||||
8
game.py
8
game.py
@ -100,6 +100,8 @@ class Block():
|
||||
self.y -= 1
|
||||
self.board.place(self)
|
||||
self.reset()
|
||||
if(isCollision(self, self.board)):
|
||||
raise Exception("GAME OVER")
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
@ -127,10 +129,15 @@ class TetrisGame():
|
||||
self.block = Block(block_id, self.board)
|
||||
|
||||
self.score = 0
|
||||
self.done = False
|
||||
|
||||
def action(self, mode):
|
||||
if mode == 'd':
|
||||
try:
|
||||
self.block.fall()
|
||||
except:
|
||||
print("GAME OVER")
|
||||
self.done = True
|
||||
elif mode == 'l':
|
||||
self.block.shiftLeft()
|
||||
elif mode == 'r':
|
||||
@ -139,7 +146,6 @@ class TetrisGame():
|
||||
self.block.rotate()
|
||||
|
||||
self.score += self.board.checkScore()
|
||||
print("SCORE:", self.score)
|
||||
|
||||
def view(self):
|
||||
return view(self.board, self.block)
|
||||
|
||||
Loading…
Reference in New Issue
Block a user