コード例 #1
0
def play(game: Tetris,
         brain: TetrisGenome,
         time_out=None,
         tick_callback=None) -> Tetris:
    def get_col(x):
        return tuple(map(bool, game.get_col(x)))

    for tick in count():
        game.t = tick
        if game.game_over or (time_out and tick > time_out):
            break

        moves_per_tick = max(1, (10 - game.level))

        for _ in range(moves_per_tick):
            columns = tuple(get_col(x) for x in range(game.w))

            output_activations = brain(inputs=columns)

            action_idx = max(enumerate(output_activations),
                             key=itemgetter(1))[0]
            action = list(Actions)[action_idx]
            game.action(action)
            if action in [Actions.DROP_ONE, Actions.DROP_TO_BOTTOM]:
                break  # go to next tick
        else:
            game.drop(
            )  # tetromino drops 1 unit automatically at the end of the tick

        if tick_callback:
            tick_callback(game)

    return game
コード例 #2
0
def playGame():
    game = Tetris(numColors=MAXCOLORS, numColumns=10, numRows=10)
    ai = AI(function)
    # loop count variables:
    numTicks = 0
    while not game.lost:  # game loop ends when game is lost
        ai.ai(game, display=False)
        game.incrementTime()
        numTicks += 1
    return game.numLines
コード例 #3
0
def playGame():
    game = Tetris(numColors=MAXCOLORS)
    ai = AI(function)
    # loop count variables:
    numPieces = 0
    sumHeights = 0
    while not game.lost and game.numPieces < 200:  # game loop ends when game is lost
        ai.ai(game)
        game.incrementTime()
        if game.numPieces > numPieces:
            sumHeights += height(game)
            numPieces += 1
    return (game.numLines, sumHeights / numPieces)
コード例 #4
0
def train(population, seed):
    #each player plays the game until death
    #if any player plays well enough (>= DESIREDSCORE), then return tuple (score, player)
    #otherwise, evolve them and return highest score and new generation (highest score, new gen)
    scores = []
    highestScore = 0
    bestPlayer = population[0]

    for player in population:
        random.seed(seed)
        game = Tetris(
            numColumns=10,
            numRows=10)  # Use the same seed for each player, for fairness
        while (not game.lost):
            player.ai(game)  #play round of game
        random.seed()  # reset random seed

        if game.numLines > highestScore:
            highestScore = game.numLines
            bestPlayer = player

        if VERBOSE:
            print(f"{player.name()} played game with score {game.numLines}.",
                  player.weights)
        scores.append(
            game.numLines)  # adds random element to make a continuum of values

    print(
        f"{bestPlayer.name()} is the best player with a score of {highestScore}: {bestPlayer.weights}"
    )
    return scores
コード例 #5
0
ファイル: main.py プロジェクト: mathiasose/NEAT-tetris
def fitness_f(multi_genome, config):
    brain = develop_phenotype(multi_genome, config)

    easy_tetris = Tetris(w=W, h=H, tetrominoes=[I])

    easy_game = play(game=easy_tetris, brain=brain, time_out=100)

    if not easy_game.lines:
        return easy_game.score / 100

    random.seed(123456)
    proper_tetris = Tetris(w=W, h=H)
    time_out = config.fitness_threshold

    proper_game = play(game=proper_tetris, brain=brain, time_out=time_out)

    return proper_game.score
コード例 #6
0
def baseline(seed):
    random.seed(seed)
    game = Tetris(numColumns=10, numRows=10)
    baselineAI = AI(baselineFunction)
    while (not game.lost):
        baselineAI.aiSequence(game)
    random.seed()

    if VERBOSE: print(f"Baseline AI played game with score {game.numLines}.")
    return game.numLines
コード例 #7
0
def playGame():
    game = Tetris(numColors=MAXCOLORS, seed=int(time.time()))
    ai = AI(func1)

    game2 = Tetris(numColors=MAXCOLORS, seed=int(time.time()))
    ai2 = AI(func2)

    render(game, game2)

    pressedKeys = [-1, -1, -1, -1]  # up, down, left, right
    while not game.lost and not game2.lost:  # game loop ends when game is lost
        for event in pygame.event.get():  # event handling loop
            if event.type == pygame.QUIT:
                terminate()  # exit game

        # increment time (move blocks down)
        ai.aiSequence(game)
        ai2.aiSequence(game2)
        render(game, game2)

        FPSCLOCK.tick(FPS)
    return "Player 2 (Will) won" if game.lost else "Player 1 (Bill) won"
コード例 #8
0
def playGame():
    game = Tetris(numColors=MAXCOLORS)
    ai = AI()

    # a dictionary of pygame buttons and their functions:
    global AI_BUTTON
    AI_BUTTON = pygame.Rect(
        (WINDOWWIDTH - 122, 300, 50, 30))  # ai enable button

    render(game)

    # loop count variables:
    numTicks = 0
    timeSinceIncrement = 0

    pressedKeys = [-1, -1, -1, -1]  # up, down, left, right
    while not game.lost:  # game loop ends when game is lost

        if INPUT: handleInput(game, pressedKeys, numTicks)
        else:
            for event in pygame.event.get():  # event handling loop
                if event.type == pygame.QUIT:
                    terminate()  # exit game

        # increment time (move blocks down)
        if timeSinceIncrement > DELAY:  # number of ticks between time increments

            if not INPUT: ai.ai(game)

            game.incrementTime()
            timeSinceIncrement = 0
            render(game)

        FPSCLOCK.tick(FPS)
        numTicks += 1
        timeSinceIncrement += 1
    return "Game Over"
コード例 #9
0
 def play(self):
     self.counter += 1
     initial_state = GameState()
     tetris = Tetris(block_factories=self.block_factories,
                     initial_state=initial_state)
     self.player.game_count += 1
     total_score = 0
     while not tetris.is_lost():
         if self.player.should_render:
             self.render(tetris)
         move = self.player.make_move(tetris.game_state,
                                      tetris.current_block)
         score = tetris.handle_move(move)
         total_score += score
         if score:
             self.player.give_reward(score)
     # For losing. Bitch as hoe
     self.analytics.log_game(tetris.game_state, total_score)
     self.analytics.print_analytics(total_score)
     squares_filled = 0
     for line in tetris.game_state.state:
         for cell in line:
             squares_filled += 1 if not cell.empty else 0
     self.player.give_reward(-100)
コード例 #10
0
def playGame():
    seed = int(time.time())
    game = Tetris(numColors=MAXCOLORS, seed=seed)
    aiGame = Tetris(numColors=MAXCOLORS, seed=seed)
    ai = AI()
    render(game, aiGame)

    DELAY = 20  # delay between each incrementTime

    # loop count variables:
    numTicks = 0
    timeSinceIncrement = 0
    level = 0
    pressedKeys = [-1, -1, -1, -1]  # up, down, left, right
    while not game.lost or aiGame.lost:  # game loop ends when game is lost

        updated = handleInput(game, pressedKeys, numTicks)
        while aiGame.numTurns < game.numTurns:
            ai.ai(aiGame)
            aiGame.incrementTime()
            if game.numTurns - aiGame.numTurns % 10 == 0 or game.numTurns - aiGame.numTurns % 5 < 10:
                render(game, aiGame)
        if updated:
            render(game, aiGame)
        if timeSinceIncrement > DELAY:  # number of ticks between time increments
            game.incrementTime()
            timeSinceIncrement = 0
            render(game, aiGame)
        if game.numLines // 10 > level:
            level = game.numLines // 10
            DELAY = DELAY * 0.8

        FPSCLOCK.tick(FPS)
        numTicks += 1
        timeSinceIncrement += 1

    return "Game Over" if game.lost else "You Win!"
コード例 #11
0
ファイル: dqn_train.py プロジェクト: Wangzzh/Tetris_RL
numEpisodes = 10000
maxStepPerEpisode = 2000
learningRate = 0.03

# rendering
render = True
renderStepDuration = 50
renderEpisodeDuration = 20

# initialization
policyNet = TetrisDQN()
targetNet = TetrisDQN()
policyNet.to(device)
targetNet.to(device)
memory = ReplayMemory(memoryCapacity)
tetris = Tetris()
optimizer = optim.RMSprop(policyNet.parameters(), lr=learningRate)

numSteps = 0
bestEpisodeReward = -1000
done = True

# save results
currentTime = datetime.datetime.now()
timeString = currentTime.strftime("%Y-%m-%d-%H-%M-%S")
if not os.path.exists("results"):
    os.mkdir("results")
directory = "results/" + timeString + "/"
os.mkdir(directory)
configFile = open(directory + "config.txt", "w")
configFile.writelines([
コード例 #12
0
DISPLAY_WITH = 64
DISPLAY_HEIGHT = 64

input_control = InputControl()

im_arrow_left = img.imread('images/left_arrow.png')
im_arrow_left = np.transpose(im_arrow_left, (1, 0, 2)) * 255

im_arrow_right = img.imread('images/right_arrow.png')
im_arrow_right = np.transpose(im_arrow_right, (1, 0, 2)) * 255

screen = Display(DISPLAY_WITH, DISPLAY_HEIGHT)
pygame.init()
pygame.display.set_caption('Stefan')

awesome_games = [SensorLandGame(), Tetris(), FlexChainGame()]

#Do the selection menu only left and right are required
game_index = 0
iterations = 0
screen.show()
show_arrows = True
#Init display
running = True
while running:
    iterations += 1
    selected_game = awesome_games[game_index]
    screen.show_image(selected_game.get_title_image())
    if iterations % 5 == 0:
        show_arrows = not show_arrows
    if show_arrows:
コード例 #13
0
ファイル: tetris_test.py プロジェクト: Wangzzh/Tetris_RL
from tetris.tetris import Tetris

T = Tetris(render=True)

T.start()
T.print_state()
while True:
    action = int(input("Action: "))
    if action < 0:
        T.start()
    else:
        T.step(action)
    T.print_state()
コード例 #14
0
def playScreen(window):
    # Play screen:
    game = Tetris(20, 10)
    display(game, window)
    counter = time.time()
    delay = 1
    acceleration = 1
    while 1:
        try:
            key = window.getkey()
            if key == 'q':
                quit()
            if key == 's' or key == 'KEY_DOWN':
                game.incrementTime()
            if key == 'a' or key == 'KEY_LEFT':
                game.translateActiveLeft()
            if key == 'd' or key == 'KEY_RIGHT':
                game.translateActiveRight()
            if key == 'w' or key == 'KEY_UP':
                game.rotateActiveClockwise()
            if key == ' ':
                game.hardDrop()
            if key in ['{}'.format(i) for i in range(8)]:
                if key == '0':
                    game.autoChoice = True
                    game.next = randint(1, 7)
                else:
                    game.autoChoice = False
                    game.next = int(key)
            display(game, window)
        except Exception as e:
            # No input
            current = time.time()
            if counter + delay < current:
                game.incrementTime()
                display(game, window)
                counter = current
                delay = 10**(5 - float(acceleration)) / (
                    game.numTurns + 10**(5 - float(acceleration)))