Exemple #1
0
    def next_generation(self, bots, generation):
        bots.sort(key=lambda x: x[0].average_score, reverse=True)

        bots = bots[:4]
        for bot, data in bots:
            print('  {} av_score = {}'.format(bot, bot.average_score))
        for i in range(3):
            bot = bots[0][0].mutation(self.Mutations)
            bot.change_name('bot_{}'.format(generation))
            bot.when_born = generation
            data = GameData()
            bots.append((bot, data))

        for i in range(2):
            bot = bots[1][0].mutation(self.Mutations)
            bot.change_name('bot_{}'.format(generation))
            bot.when_born = generation
            data = GameData()
            bots.append((bot, data))

        bot = bots[2][0].mutation(self.Mutations)
        bot.change_name('bot_{}'.format(generation))
        bot.when_born = generation
        data = GameData()
        bots.append((bot, data))
        return bots
Exemple #2
0
 def test_head_view_bits(self):
     bits = GameData.head_view_bits([[True] * 3, [True] * 3, [True] * 3])
     self.assertEqual(0b111111111, bits)
     bits = GameData.head_view_bits([[True] * 3, [False] * 3, [True] * 3])
     self.assertEqual(0b111000111, bits)
     bits = GameData.head_view_bits([[False] * 3, [False] * 3, [True] * 3])
     self.assertEqual(0b111000000, bits)
Exemple #3
0
class GameServer:
    def __init__(self):
        HOST = ''                 # Symbolic name meaning the local host
        PORT = 8387               # Arbitrary non-privileged port
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind((HOST, PORT))
        s.listen(1)
        print 'listening'
        self.gameData = GameData()
        self.methods = {'getLandmarks':self.getLandmarks,
                        'addScore':self.addScore,
                        'startMultiplayerGame':self.startMultiplayerGame,
                        'addMultiplayerScore':self.addMultiplayerScore,
                    }
        self.player1 = None
        self.player2 = None
        
        while True:
            print 'while true'
            conn, addr = s.accept()
            print 'Connected by', addr
            request = conn.recv(1024)
            if not request: break
            methodString, argument = request.split(',')
            method = self.methods[methodString]
            method(argument, conn)
                
        
    def getLandmarks(self, difficulty, conn):        
        landmarks = self.gameData.getLandmarks(difficulty)
        landmarks = pickle.dumps(landmarks)
        data = 'yes@%s$' % landmarks
        print conn.sendall(data)
    
    def addScore(self, score, conn):
        self.gameData.addScore(score)
        scores = 'no@%s' % self.gameData.getScores()
        conn.send(scores)
    
    def startMultiplayerGame(self, player, conn):
        name, address = player.split('$')
        if self.player1 == None:
            self.player1 = Player(name, address)
            player2Server = Player2Server(self)
            player2Server.start()
            return '%s has joined the game, now waiting for a second player' % name
        if self.player2 == None:
            self.player2 = Player(name, address)
            
    def gotPlayer2(self):
        pass
            
    def addMultiplayerScore(self, score):
        pass
    def decide(self, info: GameData) -> str:
        print("Kopf ist bei ", info.head_x, " / ", info.head_y)
        print("Abstand zur Wand im Norden: ", info.walldistance_n)

        # Versuche näher zum Futter zu kommen
        if info.food_x < info.head_x:
            # Eigentlich return "west"
            # Aber lass mal vorher prüfen, ob das überhaupt geht
            if info.can_move_to(info.head_x - 1, info.head_y):
                return "west"
        if info.food_x > info.head_x:
            #Eigentlich return "east"
            if info.can_move_to(info.head_x + 1, info.head_y):
                return "east"
        if info.food_y < info.head_y:
            #Eigentlich return "north"
            if info.can_move_to(info.head_x , info.head_y - 1):
                return "north"
        if info.food_y > info.head_y:
            #Eigentlich return "south"
            if info.can_move_to(info.head_x , info.head_y + 1):
                return "south"

        # Die Schlange konnte nicht in Richtung Futter laufen, weil der Weg dorthin blockiert war
        # Daher: irgendeinen Weg suchen, wo man hinlaufen kann
        #if info.can_move_to(info.head_x - 1, info.head_y):
        #    return "west"
        #if info.can_move_to(info.head_x + 1, info.head_y):
        #    return "east"
        #if info.can_move_to(info.head_x, info.head_y - 1):
        #    return "north"
        #if info.can_move_to(info.head_x, info.head_y + 1):
        #    return "south"

        for max_distance in range(5, 0, -1):
            can_walk_north = True
            can_walk_east = True
            can_walk_south = True
            can_walk_west = True
            for distance in range(1, max_distance + 1):
                if not info.can_move_to(info.head_x - distance, info.head_y):
                    can_walk_west = False
                if not info.can_move_to(info.head_x + distance, info.head_y):
                    can_walk_east = False
                if not info.can_move_to(info.head_x, info.head_y - distance):
                    can_walk_north = False
                if not info.can_move_to(info.head_x, info.head_y + distance):
                    can_walk_south = False
            if can_walk_west:
                return "west"
            if can_walk_east:
                return "east"
            if can_walk_north:
                return "north"
            if can_walk_south:
                return "south"

        # Nix gefunden? Dann hab ich mich wohl eingezingelt
        return "straight"
Exemple #5
0
    def get_head_view_with_food(info: GameData):
        surrounding = [[0 for x in range(-1, 2)] for x in range(-1, 2)]
        for dy in range(-1, 2):
            for dx in range(-1, 2):
                can_move = info.can_move_to(info.head_x + dx, info.head_y + dy)
                is_food = info.is_food(info.head_x + dx, info.head_y + dy)

                if not can_move:
                    surrounding[dy + 1][dx + 1] = BLOCKED
                elif can_move and not is_food:
                    surrounding[dy + 1][dx + 1] = FREE
                elif can_move and is_food:
                    surrounding[dy + 1][dx + 1] = FOOD

        return surrounding
    def decide(self, info: GameData) -> str:
        if info.head_x < info.food_x:
            if info.can_move_to(info.head_x + 1, info.head_y):
                return "east"
        if info.head_x > info.food_x:
            if info.can_move_to(info.head_x - 1, info.head_y):
                return "west"
        if info.head_y < info.food_y:
            if info.can_move_to(info.head_x, info.head_y + 1):
                return "south"
        if info.head_y > info.food_y:
            if info.can_move_to(info.head_x, info.head_y - 1):
                return "north"

        return "north"
Exemple #7
0
 def __init__(self):
     HOST = ''                 # Symbolic name meaning the local host
     PORT = 8387               # Arbitrary non-privileged port
     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     s.bind((HOST, PORT))
     s.listen(1)
     print 'listening'
     self.gameData = GameData()
     self.methods = {'getLandmarks':self.getLandmarks,
                     'addScore':self.addScore,
                     'startMultiplayerGame':self.startMultiplayerGame,
                     'addMultiplayerScore':self.addMultiplayerScore,
                 }
     self.player1 = None
     self.player2 = None
     
     while True:
         print 'while true'
         conn, addr = s.accept()
         print 'Connected by', addr
         request = conn.recv(1024)
         if not request: break
         methodString, argument = request.split(',')
         method = self.methods[methodString]
         method(argument, conn)
Exemple #8
0
def situation_number(kantenlänge: int, maske: str, field: GameData):
    maske = maske.replace(" ", "")

    beginn = int(-(kantenlänge - 1) / 2)
    ende = int((kantenlänge - 1) / 2)
    auschnitt = []
    for deltay in range(beginn, ende + 1):
        for deltax in range(beginn, ende + 1):
            print(deltax, deltay)
            kästchen_x = field.head_x + deltax
            kästchen_y = field.head_y + deltay
            leer = field.can_move_to(kästchen_x, kästchen_y)
            if leer:
                auschnitt.append(0)
            else:
                auschnitt.append(1)
    # Schritt 2: in eine Zahl umwandeln
    wertigkeit = 1
    summe = 0
    # for Binearziffer in auschnitt:
    for stelle in range(kantenlänge**2):
        Binearziffer = auschnitt[stelle]
        maskiert = int(maske[stelle])
        if maskiert != 0:
            if Binearziffer == 1:
                summe += wertigkeit
            wertigkeit = wertigkeit * 2

    return summe
Exemple #9
0
 def decode_json(self, text):
     data = json.loads(text)
     name = data['name']
     description = data['description']
     price = data['offers']['price']
     rating = data['aggregateRating']['ratingValue']
     url = self.game_url
     self.returnElements = GameData(url, name, price, rating, description)
Exemple #10
0
class SelfPlay:
    def __init__(self, game, network, playouts):
        self.mcts = MCTS(game, network, playouts)
        self.gd = GameData()

    def play(self):
        root = self.mcts.root
        self.mcts.evaluate_first_state(root)

        while root.state[4] == GAME_IN_PROGRESS:
            self.mcts.do_playouts(root)
            root, pi = self.mcts.choose_move(root, True)
            self.gd.add_move_to_record(root, pi)
            root.parent = None
            self.mcts.add_dirichlet_noise_to_probabilities(root)

        self.mcts.print_result(root.state[4])
        self.gd.make_game_record(
            True) if root.state[4] == DRAW else self.gd.make_game_record(False)
 def situation_berechnen(self, field: GameData):
     ergebnis = 0
     wertigkeit = 1
     for i in range(0, len(self.vektoren)):
         vektor = tuple(self.vektoren[i])
         if field.can_move_to(field.head_x + vektor[0],
                              field.head_y + vektor[1]) == False:
             ergebnis += wertigkeit
         wertigkeit *= 2
     return ergebnis
Exemple #12
0
    def minMax(self, board, isPlaying, depth, alpha, beta):
        output = GameData()
        score = board.getScore()

        currentPlayer = 1
        if isPlaying:
            currentPlayer = 2

        if board.isFinished() or depth <= 0:
            output.column = None
            output.score = score
            return output

        for i in range(0, board.columns):
            b = copy.deepcopy(board)
            if b.addChip(currentPlayer, i):
                nextMove = self.minMax(b, not isPlaying, depth - 1, alpha,
                                       beta)
                if isPlaying:
                    if output.column == None or nextMove.score > output.score:
                        output.column = i
                        alpha = output.score = nextMove.score
                else:
                    if output.column == None or nextMove.score < output.score:
                        output.column = i
                        alpha = output.score = nextMove.score
            if (alpha >= beta):
                break

        return output
Exemple #13
0
    def decide(self, info: GameData) -> str:
        if info.head_y == 0:
            if info.head_x == 0:
                return "south"
            return "west"

        if info.walldistance_e == 0:
            if info.head_y > 0:
                return "north"
        if info.walldistance_s == 0:
            return "east"

        if info.head_x < info.field_width - 2:
            if not info.is_body(info.head_x + 1, info.head_y):
                return "east"
        if info.head_x > 0:
            if not (info.is_body(info.head_x - 1, info.head_y)):
                return "west"

        if info.walldistance_e == 1:
            return "south"

        return "south"
Exemple #14
0
    def start(self):
        bots = []
        bots.append((AI_2048(name='bot_-1',
                             file_name='bot_-1_195weights'), GameData()))
        bots.append((AI_2048(name='bot_-1',
                             file_name='bot_7_804weights'), GameData()))
        bots.append((AI_2048(name='bot_-1',
                             file_name='bot_7_862weights'), GameData()))
        bots.append((AI_2048(name='bot_-1',
                             file_name='bot_8_490weights'), GameData()))
        for _ in range(4):
            bots.append((AI_2048(training=True, name='bot_-1'), GameData()))

        for generation in range(self.generations):
            print('Generation №{}'.format(generation))
            average = 0
            for bot, data in bots:
                for _ in range(30):
                    self.bot_play(bot, data)

                average += bot.average_score

            average = round(average / 10)
            print('      average = {}'.format(average))
            if self.drawing:
                self.Y.append(average)
            bots = self.next_generation(bots, generation)

        bots.sort(key=lambda x: x[0].average_score, reverse=True)
        for bot, data in bots[:4]:
            bot.save()

        if self.drawing:
            plt.plot(self.X, self.Y)
            plt.axis([0, self.generations, 0, 10000])
            plt.grid()
            plt.show()
    def init_game(self):
        pygame.init()
        self.game_data = GameData()

        self.white = (255, 255, 255)

        self.screen = pygame.display.set_mode((self.game_data.display_width, self.game_data.display_height))
        pygame.display.set_caption('Frogger')
        self.clock = pygame.time.Clock()
        

        self.frogsNum = 200  # Number of frogs spawned per generation
        self.done = False   # Application is still running
        self.turtleCounter = 0  # Timer for turtle state
        self.fps = 15  # Simulation speed (actions per second)
def situation_number(kantenlänge: int, maske: str, field: GameData):
    maske = maske.replace(" ", "")

    # Schritt 1: wir suchen den Ausschnitt um den Kopf herum
    # Bei einer Kantenlänge von 3 müssen wir bei -1 links vom Kopf anfangen
    # und bei +1 rechts vom Kopf aufhören.
    # Kantenlänge 5: von -2 bis +2
    # Kantenlänge 7: von -3 bis +3
    beginn = int(-(kantenlänge - 1) / 2)
    ende = int((kantenlänge - 1) / 2)
    ausschnitt = []
    for deltay in range(beginn, ende + 1):
        for deltax in range(beginn, ende + 1):
            print(deltax, deltay)
            kästchen_x = field.head_x + deltax
            kästchen_y = field.head_y + deltay
            leer = field.can_move_to(kästchen_x, kästchen_y)
            if leer:
                ausschnitt.append(0)
            else:
                ausschnitt.append(1)

    # Schritt 2: in eine Zahl umwandeln
    wertigkeit = 1
    summe = 0
    # for binärziffer in ausschnitt:
    for stelle in range(kantenlänge**2):
        binärziffer = ausschnitt[stelle]
        maskiert = int(maske[stelle])
        if maskiert != 0:
            if binärziffer == 1:
                summe += wertigkeit
            wertigkeit = wertigkeit * 2
    # 0   1    0   0   1   0  0  0  0  Eingang
    # 1   1    1   1   0   1  1  1  1  Maske
    # 128 64   32  16      8  4  2  1

    return summe
Exemple #17
0
    def decide(self, info: GameData) -> str:
        # Strategie: zum Futter laufen
        if info.head_x < info.food_x:  # Liegt Futter im Osten?
            if info.can_move_to(info.head_x + 1,
                                info.head_y):  # Kann ich nach Osten?
                return "east"

        if info.head_x > info.food_x:  # Liegt Futter im Westen?
            if info.can_move_to(info.head_x - 1,
                                info.head_y):  # Kann ich nach Westen?
                return "west"

        if info.head_y < info.food_y:  # Liegt Futter im Süden?
            if info.can_move_to(info.head_x,
                                info.head_y + 1):  # Kann ich nach Süden?
                return "south"

        if info.head_y > info.food_y:  # Liegt Futter im Norden?
            if info.can_move_to(info.head_x,
                                info.head_y - 1):  # Kann ich nach Norden?
                return "north"

        # Der direkte Weg zum Futter ist wohl versperrt
        # Strategie: so weiterlaufen wie bisher
        if info.direction == "east":  # Laufe ich nach Osten?
            if info.can_move_to(info.head_x + 1,
                                info.head_y):  # Kann ich weiter nach Osten?
                return "east"

        if info.direction == "west":  # Laufe ich nach Westen?
            if info.can_move_to(info.head_x - 1,
                                info.head_y):  # Kann ich weiter nach Westen?
                return "west"

        if info.direction == "south":  # Laufe ich nach Süden?
            if info.can_move_to(info.head_x, info.head_y +
                                1):  # Kann ich weiter nach Süden?
                return "south"

        if info.direction == "north":  # Laufe ich nach Westen?
            if info.can_move_to(info.head_x, info.head_y -
                                1):  # Kann ich weiter nach Norden?
                return "north"

        # Weiter wie bisher geht nicht
        # Strategie: Egal wohin, bloß nicht sterben...
        if info.can_move_to(info.head_x + 1,
                            info.head_y):  # Kann ich nach Osten?
            return "east"
        if info.can_move_to(info.head_x - 1,
                            info.head_y):  # Kann ich nach Westen?
            return "west"
        if info.can_move_to(info.head_x,
                            info.head_y + 1):  # Kann ich nach Süden?
            return "south"
        if info.can_move_to(info.head_x,
                            info.head_y - 1):  # Kann ich nach Norden?
            return "north"

        # Öhm ... alle Richtungen versperrt?
        # Dann lieber auf einer Südseeinsel sterben
        return "south"
Exemple #18
0
def main(argv):

    # process command line arguments
    if DEBUG:
        print(f"len(argv): {len(argv)}")

    if len(argv) >= 2:
        player_name = '0'
        gameno = argv[1]
    else:
        usage()
        sys.exit(1)

    if len(argv) >= 3:
        board_file = argv[2]
    if len(argv) >= 4:
        player_files = argv[3:]

    # initialize data object
    data = GameData(gameno, player_name)

    while True:

        # load the gamedata
        data.load()

        players = data.getPlayers()
        player_obj = data.getPlayerObj(player_name)
        board = data.getBoard()
        seen_board = data.getSeenBoard()
        size_x = data.getSizeX()
        size_y = data.getSizeY()
        new_game = data.getNewGame()
        game_password = data.getGamePassword()

        # if this is the first time the server is run, you need to reset the initial password from blank here
        password = data.getGamePassword()

        # interactive mode
        while new_game:
            # read line from stdin + tokenize it
            print(f"{argv[0]}> ", flush=True, end='')
            line = sys.stdin.readline().rstrip()
            tokens = line.split()

            # ignore empty lines
            if len(tokens) == 0:
                continue

            # command help
            elif tokens[0] == 'help':
                command_help()
                continue

            # show - board, units
            elif tokens[0] == 'show':
                if DEBUG:
                    print(f"len(tokens): {len(tokens)}")
                if len(tokens) == 1:
                    print("invalid show command")
                    continue
                elif tokens[1] == 'board':
                    if seen_board != None:
                        if DEBUG:
                            print("showing seen board")
                        seen_board.print()
                    elif board == None:
                        print("must create board - set size and commit")
                    else:
                        board.print(player_obj)

                elif tokens[1] == 'types':
                    for player in players.keys():
                        if 'types' in players[player].keys():
                            for types in players[player]['types'].keys():
                                for unit_name in players[player]['types'].keys(
                                ):
                                    unit_type = players[player]['types'][
                                        unit_name]
                                    print(
                                        f"player: {player}, name: {unit_type['name']}, symbol: {unit_type['symbol']}, attack: {unit_type['attack']}, health: {unit_type['health']}, energy: {unit_type['energy']}"
                                    )

                elif tokens[1] == 'players':
                    for player in players.keys():
                        print(
                            f"name: {player}, email: {players[player]['email']}"
                        )
                elif tokens[1] == 'units':
                    if seen_board != None:
                        if DEBUG:
                            print("showing seen units")
                        print(seen_board.listUnits())
                    elif board == None:
                        print("must create board - set size and commit")
                    else:
                        print(board.listUnits(player_obj))
                elif tokens[1] == 'pending':
                    for player in players.keys():
                        if 'moves' in players[player].keys():
                            print(
                                f"player: {player}, moves: {players[player]['moves']}"
                            )
                else:
                    print("invalid show command")
                    continue

            # set - size, player
            elif tokens[0] == 'set':
                if DEBUG:
                    print(f"len(tokens): {len(tokens)}")
                if len(tokens) == 1:
                    print("invalid set command")
                    continue
                elif tokens[1] == 'board':
                    if player_name != '0':
                        print(
                            "only the game admin (player '0') can set board size"
                        )
                        continue
                    if board != None:
                        print("can't resize an existing board")
                        continue
                    if len(tokens) != 4:
                        print("must provide x and y for size")
                        continue
                    try:
                        size_x = int(tokens[2])
                        size_y = int(tokens[3])
                        # immediately create the board object
                        board = Board(size_x, size_y)
                        data.setBoard(board)
                    except:
                        print("x and y must be a numbers")
                        continue
                    if size_x < 2:
                        print("x must be greater than 1")
                    if size_y < 2:
                        print("y must be greater than 1")
                else:
                    print("invalid set command")
                    continue

            # add - player, type, unit
            elif tokens[0] == 'add':
                if len(tokens) == 2:
                    print("invalid add command")
                    continue
                elif tokens[1] == 'player':
                    if len(tokens) != 4:
                        print("must provide 2 args for player")
                    elif new_game == False:
                        print("can't add players to an existing game")
                    else:
                        name = tokens[2]
                        players[name] = {
                            "email": tokens[3],
                            'obj': Player(tokens[2], tokens[3]),
                            'types': {}
                        }
                        password1 = getpass()
                        password2 = getpass("Reenter password: "******"User passwords must match")
                            continue
                        else:
                            players[name]["password"] = password1
                else:
                    print("invalid add command")
                    continue

            # load - player
            elif tokens[0] == 'load':
                if len(tokens) == 2:
                    print("invalid load command")
                    continue
                elif tokens[1] == 'player':
                    if len(tokens) != 3:
                        print("must provide 1 args for load player")
                    elif new_game == False:
                        print("can't add players to an existing game")
                    else:
                        player_data = {}
                        try:
                            with open(tokens[2]) as f:
                                player_data = yaml.safe_load(f)
                                if DEBUG:
                                    print("finished player data")
                        except Exception as e:
                            print(f"Error loading player file {tokens[2]} {e}")
                            continue
                        players[player_data['name']] = {
                            "email":
                            player_data['email'],
                            'obj':
                            Player(player_data['name'], player_data['email']),
                            'password':
                            player_data['password'],
                            'types':
                            player_data['types'],
                            'units':
                            player_data['units']
                        }
                elif tokens[1] == 'board':
                    if len(tokens) != 3:
                        print("must provide 1 args for load board")
                    else:
                        board_data = {}
                        try:
                            with open(tokens[2]) as f:
                                board_data = yaml.safe_load(f)
                                if DEBUG:
                                    print("finished player data")
                        except Exception as e:
                            print(f"Error loading player file {tokens[2]} {e}")
                            continue
                        size_x = int(board_data['board']['size_x'])
                        size_y = int(board_data['board']['size_y'])
                        # immediately create the board object
                        board = Board(size_x, size_y)
                        data.setBoard(board)

                else:
                    print("invalid load command")
                    continue

            # commiting the game saves all input data to yaml for the game setup step
            elif tokens[0] == 'commit':
                # do all the commit actions for the first commit
                if data.serverSave():
                    print("commit complete")
                    break
                else:
                    # commit failed, go back to interactive prompt to resolve problems
                    continue
            # leave
            elif tokens[0] == 'exit':
                sys.exit(0)
            else:
                print("invalid command")

        # do all the commit actions, this will be run when the server is non-interactive
        if new_game:
            # clear the new game flag, this supresses interactive mode for the server
            data.setNewGame(False)
        elif data.serverSave():
            print("commit complete")
        else:
            print("internal server error saving game data")
            sys.exit(1)

        # wait for player commits before restarting the load and commit cycle
        data.waitForPlayerCommit()

        # log board + units
        board.print()
        print(board.listUnits())
Exemple #19
0
 def send_data(self):
     # print("Trying to send data")
     data_to_send = GameData(self.player).get_dictionary()
     self.net.send(data_to_send)
Exemple #20
0
 def __init__(self, game, network, playouts):
     self.mcts = MCTS(game, network, playouts)
     self.gd = GameData()
Exemple #21
0
from SequenceFadeUp import SequenceFadeUp
from SequenceGroup import SequenceGroup


pinMapping = PinMap('PinMap.xml')

ledwiz = LedWiz( )
ledwiz.Connect()
gpio = ArcadeGpio( pinMapping.GetAllPinsOfDevice('GPIO') )

devices = DeviceManager()
devices.Add( "LEDWIZ", ledwiz )
devices.Add( "GPIO", gpio )
devices.ClearPins()

gamedata = GameData( 'ColorsDefault.ini', 'Colors.ini', 'controls.xml' )
gamedata.run()

marqueeBrightness = 100
fanspeed = 0


def LoadMameOutputsIni( iniFilename ):

  mappings = {}

  ini = ConfigParser.RawConfigParser()
  ini.optionxform = str  # make case sensitive
  ini.read(iniFilename)
  
  if not ini.has_section("default"):
def main(argv):

    if DEBUG:
        print(f"len(argv): {len(argv)}")

    if len(argv) == 2:
        player_name = '0'
        gameno = argv[1]
    else:
        usage()
        sys.exit(1)

    # initialize the data object
    data = GameData(gameno, player_name)

    while True:

        # load the gamedata
        data.load()

        players = data.getPlayers()
        player_obj = data.getPlayerObj(player_name)
        board = data.getBoard()
        seen_board = data.getSeenBoard()
        size_x = data.getSizeX()
        size_y = data.getSizeY()
        new_game = data.getNewGame()

        # interactive mode
        while True:
            # read line from stdin + tokenize it
            print(f"{argv[0]}> ", flush=True, end='')
            line = sys.stdin.readline().rstrip()
            tokens = line.split()

            # ignore empty lines
            if len(tokens) == 0:
                continue

            # command help
            elif tokens[0] == 'help':
                command_help()
                continue

            # show - board, units
            elif tokens[0]=='show':
                if DEBUG:
                    print(f"len(tokens): {len(tokens)}")
                if len(tokens) == 1:
                    print("invalid show command")
                    continue
                elif tokens[1] == 'board':
                    if seen_board != None:
                        if DEBUG:
                            print("showing seen board")
                        seen_board.print()
                    elif board == None:
                        print("must create board - set size and commit")
                    else:
                        board.print(player_obj)

                elif tokens[1] == 'types':
                    for player in players.keys():
                        if 'types' in players[player].keys():    
                            for types in players[player]['types'].keys():
                                for unit_name in players[player]['types'].keys():
                                    unit_type = players[player]['types'][unit_name]
                                    print(f"player: {player}, name: {unit_type['name']}, symbol: {unit_type['symbol']}, attack: {unit_type['attack']}, health: {unit_type['health']}, energy: {unit_type['energy']}")

                elif tokens[1] == 'players':
                    for player in players.keys():
                        print(f"name: {player}, email: {players[player]['email']}")
                elif tokens[1] == 'units':
                    if seen_board != None:
                        if DEBUG:
                            print("showing seen units")
                        print(seen_board.listUnits())
                    elif board == None:
                        print("must create board - set size and commit")
                    else:
                        print(board.listUnits(player_obj))
                elif tokens[1] == 'pending':
                    for player in players.keys():
                        if 'moves' in players[player].keys():
                            print(f"player: {player}, moves: {players[player]['moves']}")
                else:
                    print("invalid show command")
                    continue

            # commiting the game saves all input data to yaml for the game setup step
            elif tokens[0] == 'reload':
                # relaod the data
                print("reloading")
                break
            # leave
            elif tokens[0] == 'exit':
                sys.exit(0)
            else:
                print("invalid command")
Exemple #23
0
    def initUI(self):
        self.game_data = GameData()

        self.new_game_button = QPushButton('Новая Игра', self)
        self.new_game_button.setStyleSheet(self.button_style %
                                           (self.new_game_color.name(), 5, 20,
                                            self.main_text_color.name(), 10))
        self.new_game_button.move(10, 50)

        self.new_game_button.clicked.connect(self.new_game)

        self.square = QFrame(self)
        self.square.setGeometry(0, 100, 380, 380)
        self.square.setStyleSheet(self.style % (self.main_color.name(), 5))

        self.result_label = QLabel('Результат\n0', self)
        self.crt_progress_label = QLabel('За последний ход\n0', self)
        self.moves_counter = QLabel('Ходов сделано\n0', self)

        self.result_label.setStyleSheet(
            self.button_style %
            (self.main_color.name(), 5, 20, self.main_text_color.name(), 5))
        self.result_label.setAlignment(Qt.AlignCenter)
        self.crt_progress_label.setStyleSheet(
            self.button_style %
            (self.main_color.name(), 5, 20, self.main_text_color.name(), 5))
        self.crt_progress_label.setAlignment(Qt.AlignCenter)
        self.moves_counter.setStyleSheet(
            self.button_style %
            (self.main_color.name(), 5, 20, self.main_text_color.name(), 5))
        self.moves_counter.setAlignment(Qt.AlignCenter)

        self.result_label.move(400, 100)
        self.crt_progress_label.move(400, 180)
        self.moves_counter.move(400, 260)

        self.image_w = QPixmap(r'images\w.png')
        self.image_d = QPixmap(r'images\d.png')
        self.image_s = QPixmap(r'images\s.png')
        self.image_a = QPixmap(r'images\a.png')
        self.image_w_red = QPixmap(r'images\w_red.png')
        self.image_d_red = QPixmap(r'images\d_red.png')
        self.image_s_red = QPixmap(r'images\s_red.png')
        self.image_a_red = QPixmap(r'images\a_red.png')
        self.label_w = QLabel(self)
        self.label_d = QLabel(self)
        self.label_s = QLabel(self)
        self.label_a = QLabel(self)

        self.label_w.setPixmap(self.image_w)
        self.label_d.setPixmap(self.image_d)
        self.label_s.setPixmap(self.image_s)
        self.label_a.setPixmap(self.image_a)

        self.label_w.move(474, 374)
        self.label_d.move(528, 426)
        self.label_s.move(474, 426)
        self.label_a.move(420, 426)

        self.grid = QGridLayout()
        self.grid.setSpacing(4)
        self.grid.setContentsMargins(4, 4, 4, 4)

        self.square_go = QFrame(self)
        self.square_go.setGeometry(0, 100, 380, 380)
        self.square_go.setStyleSheet(
            'QWidget { background-color: rgba(240, 240, 240, 90); border-radius: 5px}'
        )
        self.square_go.setVisible(False)

        self.game_over_label = QLabel('GAME OVER', self)
        self.game_over_label.setStyleSheet(
            self.button_style %
            (self.main_color.name(), 5, 20, self.main_text_color.name(), 10))
        self.game_over_label.setAlignment(Qt.AlignCenter)
        self.game_over_label.setVisible(False)
        self.game_over_label.move(130, 270)

        self.square.setLayout(self.grid)
        self.refresh_grid()

        self.timer = QTimer()

        ico = QIcon(r'images\2048_icon.ico')
        self.setWindowIcon(ico)
        self.setFixedSize(640, 480)
        self.setWindowTitle('2048')
        self.show()
 def get_info(self) -> GameData:
     info = GameData()
     info.snake_length = len(self.snake)
     info.head_x = self.snake[0][0]
     info.head_y = self.snake[0][1]
     info.direction = {
         (0, 1): "south",
         (0, -1): "north",
         (1, 0): "east",
         (-1, 0): "west"
     }[self.direction]
     info.walldistance_n = info.head_y
     info.walldistance_s = self.field.height - info.head_y - 1
     info.walldistance_w = info.head_x
     info.walldistance_e = self.field.width - info.head_x - 1
     info.food_x = self.food[0]
     info.food_y = self.food[1]
     info.field = self.field
     info.body = self.snake  # copy.deepcopy(self.snake)
     info.game_over = self.is_game_over()
     return info
Exemple #25
0
class GameGui(QWidget):
    game_over = False
    button_style = 'QWidget { background-color: %s; border-radius: %spx; font: %spx; color: %s; padding: %spx;}'
    style = 'QWidget { background-color: %s; border-radius: %spx}'

    main_color = QColor(187, 173, 160)
    new_game_color = QColor(143, 122, 102)
    number_color = QColor(119, 110, 101)
    main_text_color = QColor(248, 246, 242)
    empty_cell = QColor(205, 193, 180)
    frames_color = {
        0: QColor(238, 228, 218),
        2: QColor(238, 228, 218),
        4: QColor(237, 224, 200),
        8: QColor(242, 177, 121),
        16: QColor(245, 149, 99),
        32: QColor(246, 124, 95),
        64: QColor(246, 94, 59),
        128: QColor(237, 207, 114),
        256: QColor(237, 204, 97),
        512: QColor(237, 200, 80),
        1024: QColor(237, 197, 63),
        2048: QColor(237, 194, 46)
    }
    frames_color_other = QColor(60, 58, 50)
    moves = {
        '87': 0,
        '68': 1,
        '83': 2,
        '65': 3,
        '1062': 0,
        '1042': 1,
        '1067': 2,
        '1060': 3
    }

    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.initUI()

    def initUI(self):
        self.game_data = GameData()

        self.new_game_button = QPushButton('Новая Игра', self)
        self.new_game_button.setStyleSheet(self.button_style %
                                           (self.new_game_color.name(), 5, 20,
                                            self.main_text_color.name(), 10))
        self.new_game_button.move(10, 50)

        self.new_game_button.clicked.connect(self.new_game)

        self.square = QFrame(self)
        self.square.setGeometry(0, 100, 380, 380)
        self.square.setStyleSheet(self.style % (self.main_color.name(), 5))

        self.result_label = QLabel('Результат\n0', self)
        self.crt_progress_label = QLabel('За последний ход\n0', self)
        self.moves_counter = QLabel('Ходов сделано\n0', self)

        self.result_label.setStyleSheet(
            self.button_style %
            (self.main_color.name(), 5, 20, self.main_text_color.name(), 5))
        self.result_label.setAlignment(Qt.AlignCenter)
        self.crt_progress_label.setStyleSheet(
            self.button_style %
            (self.main_color.name(), 5, 20, self.main_text_color.name(), 5))
        self.crt_progress_label.setAlignment(Qt.AlignCenter)
        self.moves_counter.setStyleSheet(
            self.button_style %
            (self.main_color.name(), 5, 20, self.main_text_color.name(), 5))
        self.moves_counter.setAlignment(Qt.AlignCenter)

        self.result_label.move(400, 100)
        self.crt_progress_label.move(400, 180)
        self.moves_counter.move(400, 260)

        self.image_w = QPixmap(r'images\w.png')
        self.image_d = QPixmap(r'images\d.png')
        self.image_s = QPixmap(r'images\s.png')
        self.image_a = QPixmap(r'images\a.png')
        self.image_w_red = QPixmap(r'images\w_red.png')
        self.image_d_red = QPixmap(r'images\d_red.png')
        self.image_s_red = QPixmap(r'images\s_red.png')
        self.image_a_red = QPixmap(r'images\a_red.png')
        self.label_w = QLabel(self)
        self.label_d = QLabel(self)
        self.label_s = QLabel(self)
        self.label_a = QLabel(self)

        self.label_w.setPixmap(self.image_w)
        self.label_d.setPixmap(self.image_d)
        self.label_s.setPixmap(self.image_s)
        self.label_a.setPixmap(self.image_a)

        self.label_w.move(474, 374)
        self.label_d.move(528, 426)
        self.label_s.move(474, 426)
        self.label_a.move(420, 426)

        self.grid = QGridLayout()
        self.grid.setSpacing(4)
        self.grid.setContentsMargins(4, 4, 4, 4)

        self.square_go = QFrame(self)
        self.square_go.setGeometry(0, 100, 380, 380)
        self.square_go.setStyleSheet(
            'QWidget { background-color: rgba(240, 240, 240, 90); border-radius: 5px}'
        )
        self.square_go.setVisible(False)

        self.game_over_label = QLabel('GAME OVER', self)
        self.game_over_label.setStyleSheet(
            self.button_style %
            (self.main_color.name(), 5, 20, self.main_text_color.name(), 10))
        self.game_over_label.setAlignment(Qt.AlignCenter)
        self.game_over_label.setVisible(False)
        self.game_over_label.move(130, 270)

        self.square.setLayout(self.grid)
        self.refresh_grid()

        self.timer = QTimer()

        ico = QIcon(r'images\2048_icon.ico')
        self.setWindowIcon(ico)
        self.setFixedSize(640, 480)
        self.setWindowTitle('2048')
        self.show()

    def new_game(self):
        if self.game_over:
            self.square_go.setVisible(False)
            self.game_over_label.setVisible(False)
            self.game_over = False

        self.game_data.refresh()
        self.refresh_grid()
        self.result_label.setText('Результат\n0')
        self.crt_progress_label.setText('За текущий ход\n0')
        self.moves_counter.setText('Ходов сделано\n0')
        self.result_label.update()
        self.crt_progress_label.update()
        self.moves_counter.update()
        return

    def refresh_grid(self):
        field = self.game_data.get_field()

        for i in range(4):
            for j in range(4):
                cell = field[i][j]
                num = cell.get_number()

                label = QLabel('{}'.format(num if num != 0 else ''))
                label_col = self.frames_color_other if num > 2048 else self.frames_color[
                    num]
                text_color = self.number_color if num < 8 else self.main_text_color
                if num == 0:
                    label_col = self.empty_cell
                label.setStyleSheet(
                    self.button_style %
                    (label_col.name(), 3, 30, text_color.name(), 10))
                label.setAlignment(Qt.AlignCenter)
                self.grid.addWidget(label, i, j)
        self.square.update()
        return

    def keyPressEvent(self, event):
        key = str(event.key())
        try:
            move = self.moves[key]
            if move == 0:
                self.label_w.setPixmap(self.image_w_red)
                self.label_w.update()
                self.timer.timeout.connect(self.time_out_w)
                self.timer.start(50)
            elif move == 1:
                self.label_d.setPixmap(self.image_d_red)
                self.label_d.update()
                self.timer.timeout.connect(self.time_out_d)
                self.timer.start(50)
            elif move == 2:
                self.label_s.setPixmap(self.image_s_red)
                self.label_s.update()
                self.timer.timeout.connect(self.time_out_s)
                self.timer.start(50)
            else:
                self.label_a.setPixmap(self.image_a_red)
                self.label_a.update()
                self.timer.timeout.connect(self.time_out_a)
                self.timer.start(50)

            if self.game_over:
                return

            check = self.game_data.move(move)
            if not check:
                return

            self.game_data.rand_cell()
            self.result_label.setText('Результат\n{}'.format(
                self.game_data.progress))
            self.crt_progress_label.setText('За текущий ход\n{}'.format(
                self.game_data.crt_progress))
            self.moves_counter.setText('Ходов сделано\n{}'.format(
                self.game_data.moves))
            self.result_label.update()
            self.crt_progress_label.update()
            self.moves_counter.update()
            self.game_data.crt_progress = 0
            self.refresh_grid()

            if self.game_data.check_GameOver():
                self.game_over = True
                self.square_go.setVisible(True)
                self.game_over_label.setVisible(True)
            return
        except KeyError:
            return

    def time_out_w(self):
        self.timer.stop()
        self.label_w.setPixmap(self.image_w)
        self.label_w.update()
        return

    def time_out_d(self):
        self.timer.stop()
        self.label_d.setPixmap(self.image_d)
        self.label_d.update()
        return

    def time_out_s(self):
        self.timer.stop()
        self.label_s.setPixmap(self.image_s)
        self.label_s.update()
        return

    def time_out_a(self):
        self.timer.stop()
        self.label_a.setPixmap(self.image_a)
        self.label_a.update()
        return

    def closeEvent(self, event):
        self.hide()
        event.accept()
        return
Exemple #26
0
def main(argv):

    if DEBUG:
        print(f"len(argv): {len(argv)}")

    if len(argv) == 3:
        gameno = argv[1]
        player_name = argv[2]
    else:
        usage()
        sys.exit(1)

    # initialize the data object
    data = GameData(gameno, player_name)

    # load the data 
    while True:

        # load/reload the gamedata
        data.load()

        # set the fields used in the parser
        players = data.getPlayers()
        player_obj = data.getPlayerObj(player_name)
        board = data.getBoard()
        seen_board = data.getSeenBoard()
        size_x = data.getSizeX()
        size_y = data.getSizeY()
        new_game = data.getNewGame()
        unprocessed_moves = data.getUnprocessedMoves()

        # wait 5 seconds if there are unprocessed moves and then reload
        if unprocessed_moves:
            print("waiting for turn to complete...")
            time.sleep(5)
            # restart the loop
            continue

        # interactive mode
        while True:

            # read line from stdin + tokenize it
            print(f"{argv[0]}> ", flush=True, end='')
            line = sys.stdin.readline().rstrip()
            tokens = line.split()

            # ignore empty lines
            if len(tokens) == 0:
                continue

            # command help
            elif tokens[0] == 'help':
                command_help()
                continue

            # show - board, units
            elif tokens[0]=='show':
                if DEBUG:
                    print(f"len(tokens): {len(tokens)}")
                if len(tokens) == 1:
                    print("invalid show command")
                    continue
                elif tokens[1] == 'board':
                    if seen_board != None:
                        if DEBUG:
                            print("showing seen board")
                        seen_board.print()
                    elif board == None:
                        print("must create board - set size and commit")
                    else:
                        board.print(player_obj)

                elif tokens[1] == 'types':
                    for player in players.keys():
                        if 'types' in players[player].keys():    
                            for types in players[player]['types'].keys():
                                for unit_name in players[player]['types'].keys():
                                    unit_type = players[player]['types'][unit_name]
                                    print(f"player: {player}, name: {unit_type['name']}, symbol: {unit_type['symbol']}, attack: {unit_type['attack']}, health: {unit_type['health']}, energy: {unit_type['energy']}")

                elif tokens[1] == 'players':
                    for player in players.keys():
                        print(f"name: {player}, email: {players[player]['email']}")
                elif tokens[1] == 'units':
                    if seen_board != None:
                        if DEBUG:
                            print("showing seen units")
                        print(seen_board.listUnits())
                    elif board == None:
                        print("must create board - set size and commit")
                    else:
                        print(board.listUnits(player_obj))
                else:
                    print("invalid show command")
                    continue

            # add - player, type, unit
            elif tokens[0] == 'add':
                if len(tokens) == 1:
                    print("invalid add command")
                    continue
                elif tokens[1] == 'type':
                    if len(tokens) != 7:
                        print("must provide 5 args for type")
                        continue
                    if new_game == False:
                        print("can't add types after first turn")
                        continue
                    try:
                        type_name = tokens[2]
                        symbol = tokens[3]
                        attack = tokens[4]
                        health = tokens[5]
                        energy = tokens[6]
                        obj = UnitType(type_name, symbol, int(attack), int(health), int(energy))
                        players[player_name]['types'][type_name] = {}
                        players[player_name]['types'][type_name]['name'] = type_name
                        players[player_name]['types'][type_name]['symbol'] = symbol
                        players[player_name]['types'][type_name]['attack'] = attack
                        players[player_name]['types'][type_name]['health'] = health
                        players[player_name]['types'][type_name]['energy'] = energy
                        players[player_name]['types'][type_name]['obj'] = obj
                    except Exception as e:    
                        print(f"error adding unit type: {e}")
                        continue
                elif tokens[1] == 'unit':
                    if len(tokens) != 6:
                        print("must provide 4 args for unit")
                        continue
                    if board == None:
                        print("board must be loaded in order to place units")
                        continue
                    if new_game == False:
                        print("can't add units after first turn")
                        continue
                    try:
                        type_name = tokens[2]
                        name = tokens[3]
                        x = int(tokens[4])
                        y = int(tokens[5])
                        if DEBUG:
                            print(f"{player_obj}, {x}, {y}, {name}, {players[player_name]['types'][type_name]['obj']}")
                        board.add(player_obj, x, y, name, players[player_name]['types'][type_name]['obj'])
                        board.commit()
                    except Exception as e:
                        print(f"error creating new unit {e}")
                        continue
                else:
                    print("invalid add command")
                    continue

            # move - unit
            elif tokens[0] == 'move':
                if len(tokens) != 3:
                    print("must provide 2 args for move")
                    continue
                elif board == None:
                    print("board must be loaded in order to move units")
                    continue
                elif new_game:
                    print("can't move units until after the first turn is complete")
                    continue
                try:
                    unit_name = tokens[1]
                    direction = tokens[2]
                    # TODO - make sure you implment rules to make this unique per player
                    unit = board.getUnitByName(unit_name)[0]
                    if player_name != unit.player.name:
                        print("can't move units belonging to other players")
                        continue
                    if unit.on_board == False:
                        print("can't move units not on the board")
                        continue
                    if direction == 'north':
                        direction = UnitType.NORTH
                    elif direction == 'south':
                        direction = UnitType.SOUTH
                    elif direction == 'east':
                        direction = UnitType.EAST
                    elif direction == 'west':
                        direction = UnitType.WEST
                    else:
                        print(f"invalid direction {direction}")
                        continue
                    unit.move(direction)
                    print(board.listUnits(player_obj))
                except Exception as e:
                    print(f"error moving unit {e}")
                    continue

            # commiting the game saves all input data to yaml for the game setup step
            elif tokens[0] == 'commit':
                if data.clientSave():
                    print("commit complete")
                    break

            # leave
            elif tokens[0] == 'exit':
                sys.exit(0)
            else:
                print("invalid command")