Esempio n. 1
0
    def __init__(self, riskyness):
        self.game = Game()
        self.game.init_states()

        self.coin = self.game.coin
        self.game.change_odds(0.5)

        self.money = randint(10, 40)
        self.goal = self.game.goal
        self.game.discount_rate = riskyness
Esempio n. 2
0
def min_max(board_state,
            ai,
            game,
            max_depth,
            alpha=-sys.float_info.max,
            beta=sys.float_info.max):
    # end = False
    # if time.time() - max_depth >= 5:
    #     end = True
    if not board_state.legal_moves:
        return 0, None
    best_score_move = None
    new_board = board_state.copy()
    new_game = Game()
    new_game.board_state = new_board

    for move in new_board.legal_moves:
        new_board = board_state.copy()
        new_board.push(move)

        if board_state.turn and new_board.is_checkmate():
            return 10000, move
        if not board_state.turn and new_board.is_checkmate():
            return -10000, move
        if board_state.turn and new_board.is_game_over():
            return -10, move
        if not board_state.turn and new_board.is_game_over():
            return 10, move
        if max_depth <= 1:
            score = best_move(new_board, new_game, ai)
        else:
            score, _ = min_max(new_board, ai, new_game, max_depth - 1, alpha,
                               beta)

        if board_state.turn:
            if score > alpha:
                # print(score, ' ', best_score, ' ', best_score_move)
                alpha = score
                best_score_move = move
        else:
            if score < beta:
                beta = score
                best_score_move = move
        if alpha >= beta:
            break
    # print(alpha, not game.board_state.turn)
    return alpha if not game.board_state.turn else beta, best_score_move
Esempio n. 3
0
class Player:
    def __init__(self, riskyness):
        self.game = Game()
        self.game.init_states()

        self.coin = self.game.coin
        self.game.change_odds(0.5)

        self.money = randint(10, 40)
        self.goal = self.game.goal
        self.game.discount_rate = riskyness

    def learn(self, itr):
        self.game.run(itr=itr)

    def choose(self):
        return self.game.states[self.money].best_action

    def play(self):
        result = 'win'
        tries = 0
        while self.money < self.goal:
            bet = self.choose()
            print(f'Player betting {bet} with ${self.money}')
            tries += 1
            if self.coin.flip():
                self.money += bet
            else:
                self.money -= bet
            if self.money == 0:
                result = 'lose'
                break
        print(f'You {result} after {tries} tries')
Esempio n. 4
0
def train():
    input_states = []
    output_states = []
    values = {'1/2-1/2': 0, '0-1': -1, '1-0': 1}
    game_nr = 0
    file_nr = 1
    for fn in os.listdir("KingBase2019-pgn"):
        pgn = open(os.path.join("KingBase2019-pgn", fn))

        while True:
            try:
                game = chess.pgn.read_game(pgn)
            except Exception:
                break

            try:
                result = game.headers['Result']
            except:
                break
            if result not in values:
                continue
            value = values[result]
            if value == 0:
                continue
            board = game.board()
            game_nr += 1
            print('game number ', game_nr)
            for i, move in enumerate(game.mainline_moves()):
                board.push(move)
                ser = Game(board).transform()
                input_states.append(ser)
                output_states.append(value)
            if game_nr % 2000 == 0:
                input_states = np.array(input_states)
                output_states = np.array(output_states)
                path = "train/train_" + str(file_nr) + ".npz"
                np.savez(path, input_states, output_states)
                input_states = []
                output_states = []
                file_nr += 1
    input_states = np.array(input_states)
    output_states = np.array(output_states)
    path = "train/train_" + str(file_nr) + ".npz"
    np.savez(path, input_states, output_states)
Esempio n. 5
0
# coding: latin-1 
'''
Created on Jan 22, 2013

@author: fabiofilho
'''
import pygame
from state import Game

while True:
    
    if __name__ == "__main__":
        game = Game()
        
        game.play()
        
        if game.runGame == False or game.CurrentState == False:
            break            
    
    
pygame.quit()
Esempio n. 6
0
def score_ai():
    wyniki = [0, 0, 0, 0]
    ai = []
    for fn in os.listdir("wyniki_model"):
        print(fn)
        path = os.path.join("wyniki_model", fn)
        ai.append(AI(path))
    for _ in range(1):

        game = Game()
        wynik = game_ai(ai[1], ai[0], game)
        if wynik == 0:
            wyniki[1] += 0.5
            wyniki[0] += 0.5
        elif wynik == -1:
            wyniki[0] += 1
        else:
            wyniki[1] += 1

        game = Game()
        wynik = game_ai(ai[0], ai[1], game)
        if wynik == 0:
            wyniki[1] += 0.5
            wyniki[0] += 0.5
        elif wynik == -1:
            wyniki[1] += 1
        else:
            wyniki[0] += 1

        game = Game()
        wynik = game_ai(ai[2], ai[0], game)
        if wynik == 0:
            wyniki[2] += 0.5
            wyniki[0] += 0.5
        elif wynik == -1:
            wyniki[0] += 1
        else:
            wyniki[2] += 1

        game = Game()
        wynik = game_ai(ai[0], ai[2], game)
        if wynik == 0:
            wyniki[0] += 0.5
            wyniki[2] += 0.5
        elif wynik == -1:
            wyniki[2] += 1
        else:
            wyniki[0] += 1

        game = Game()
        wynik = game_ai(ai[3], ai[0], game)
        if wynik == 0:
            wyniki[3] += 0.5
            wyniki[0] += 0.5
        elif wynik == -1:
            wyniki[0] += 1
        else:
            wyniki[3] += 1

        game = Game()
        wynik = game_ai(ai[0], ai[3], game)
        if wynik == 0:
            wyniki[3] += 0.5
            wyniki[0] += 0.5
        elif wynik == -1:
            wyniki[3] += 1
        else:
            wyniki[0] += 1

        game = Game()
        wynik = game_ai(ai[1], ai[2], game)
        if wynik == 0:
            wyniki[1] += 0.5
            wyniki[2] += 0.5
        elif wynik == -1:
            wyniki[2] += 1
        else:
            wyniki[1] += 1

        game = Game()
        wynik = game_ai(ai[2], ai[1], game)
        if wynik == 0:
            wyniki[1] += 0.5
            wyniki[2] += 0.5
        elif wynik == -1:
            wyniki[1] += 1
        else:
            wyniki[2] += 1

        game = Game()
        wynik = game_ai(ai[2], ai[3], game)
        if wynik == 0:
            wyniki[2] += 0.5
            wyniki[3] += 0.5
        elif wynik == -1:
            wyniki[3] += 1
        else:
            wyniki[2] += 1

        game = Game()
        wynik = game_ai(ai[3], ai[2], game)
        if wynik == 0:
            wyniki[3] += 0.5
            wyniki[2] += 0.5
        elif wynik == -1:
            wyniki[2] += 1
        else:
            wyniki[3] += 1

        game = Game()
        wynik = game_ai(ai[3], ai[1], game)
        if wynik == 0:
            wyniki[3] += 0.5
            wyniki[1] += 0.5
        elif wynik == -1:
            wyniki[1] += 1
        else:
            wyniki[3] += 1

        game = Game()
        wynik = game_ai(ai[1], ai[3], game)
        if wynik == 0:
            wyniki[3] += 0.5
            wyniki[1] += 0.5
        elif wynik == -1:
            wyniki[3] += 1
        else:
            wyniki[1] += 1
Esempio n. 7
0
        game = Game()
        wynik = game_ai(ai[1], ai[3], game)
        if wynik == 0:
            wyniki[3] += 0.5
            wyniki[1] += 0.5
        elif wynik == -1:
            wyniki[3] += 1
        else:
            wyniki[1] += 1


if __name__ == '__main__':
    # for fn in os.listdir("model"):
    #     path = os.path.join("model", fn)
        ai = AI()
        game = Game()
        while True:
            # try:
            #     game.board_state.push(best_move(game, ai, game.board_state.turn))
            # except:
            #     break
            # print('ai move \n')
            # print(game.board_state)
            # if game.board_state.is_checkmate():
            #     shutil.copyfile(path, "random_"+path)
            # if game.board_state.is_game_over():
            #     break
            time_move = time.time()
            # try:
            board_state = game.board_state.copy()
            move = min_max_NN.min_max_player(board_state, ai, game)
Esempio n. 8
0
    def apply(self, transaction, context):

        header = transaction.header

        signer = header.signer_public_key

        hm_payload = HmPayload.from_bytes(transaction.payload)

        hm_state = HmState(context)

        if hm_payload.action == "create":
            # Game creation was requested
            LOGGER.debug("Action: create")
            game = hm_state.get_game(hm_payload.name)
            if game:
                raise InvalidTransaction("Game '{}' already exists".format(
                    hm_payload.name))
            game = Game(name=hm_payload.name,
                        word=hm_payload.guess,
                        misses="",
                        hits="",
                        host=signer,
                        guesser="",
                        state=GAME_STATE_ONGOING)
            hm_state.set_game(hm_payload.name, game)
            LOGGER.info("Player '{}' created game '{}'".format(
                signer, hm_payload.name))
        elif hm_payload.action == "delete":
            # Game deletion was requested
            LOGGER.debug("Action: delete")
            try:
                hm_state.delete_game(hm_payload.name)
                LOGGER.info("Player '{}' deleted game '{}'".format(
                    signer, hm_payload.name))
            except KeyError:
                raise InvalidTransaction("Game '{}' doesn't exist".format(
                    hm_payload.name))
        elif hm_payload.action == "guess":
            # Someone is guessing
            LOGGER.debug("Action: guess")
            guess = hm_payload.guess.lower()
            # Game doesn't exist
            game = hm_state.get_game(hm_payload.name)
            if not game:
                raise InvalidTransaction("Game '{}' doesn't exists".format(
                    hm_payload.name))
            # Game has ended
            if game.state != GAME_STATE_ONGOING:
                raise InvalidTransaction("Game '{}' has already ended".format(
                    hm_payload.name))
            # Guess already in hits
            if guess in game.hits:
                raise InvalidTransaction(
                    "You already guessed '{}' and it was successful".format(
                        guess))
            # Guess already in misses
            if guess in game.misses:
                raise InvalidTransaction(
                    "You already guessed '{}' and it was not successful".
                    format(guess))
            LOGGER.debug("Error handling completed")
            # Compute new game
            new_misses = game.misses + guess if guess not in game.word.lower(
            ) else game.misses
            new_hits = game.hits + guess if guess in game.word.lower(
            ) else game.hits
            if set(game.word.lower()) == set(new_hits):
                new_state = GAME_STATE_WON
            elif len(new_misses) >= MAX_GUESSES:
                new_state = GAME_STATE_LOST
            else:
                new_state = GAME_STATE_ONGOING
            new_game = Game(name=game.name,
                            word=game.word,
                            misses=new_misses,
                            hits=new_hits,
                            host=game.host,
                            guesser=game.guesser,
                            state=new_state)
            LOGGER.debug("New game computation completed")
            hm_state.set_game(hm_payload.name, new_game)
            LOGGER.info("""Game stats:
                Name: '{}'
                Word: '{}'
                Misses: '{}'
                Hits: '{}'
                Host: '{}'
                Guesser: '{}'
                State: '{}'
                """.format(game.name, game.word, new_misses, new_hits,
                           game.host, game.guesser, new_state))
        else:
            raise InvalidTransaction("Unknown action '{}'".format(
                hm_payload.action))
Esempio n. 9
0
 def __init__(self):
     self.game = Game()