Ejemplo n.º 1
0
def getGame(page_data):
    json_data = json.loads(page_data)
    game = json_data['gameData']
    game_id = json_data['gamePk']
    db_game = Game.query.filter_by(game_id=game_id).first()
    if db_game:
        new_game = db_game
    else:
        params = {
            'game_id':
            game['game']['pk'],
            'type':
            game['game']['type'],
            'start_time':
            datetime.strptime(game['datetime']['dateTime'],
                              '%Y-%m-%dT%H:%M:%SZ'),
            'end_time':
            datetime.strptime(game['datetime']['endDateTime'],
                              '%Y-%m-%dT%H:%M:%SZ'),
            'game_state':
            game['status']['abstractGameState'],
            'game_state_id':
            game['status']['codedGameState']
        }
        new_game = Game(params)
        db.session.add(new_game)

    db.session.commit()
    return new_game
Ejemplo n.º 2
0
def post_game():
    data = request.get_json()
    # TODO create decorator that returns user from header
    auth_header = request.headers.get('Authorization')
    user = jwt.decode(auth_header.split(" ")[1],
                      os.environ.get('SECRET_KEY'))['user']
    user_id = json.loads(user)['id']
    try:
        game = Game(name=data['name'],
                    description=data['description'],
                    board_size=data['boardSize'],
                    game_room=data['gameRoom'],
                    player_white=user_id)
        db.session.add(game)
        db.session.commit()
        new_game_notice(room=game.game_room, game=game_schema.dumps(game))
        response = {
            'status': 'success',
            'message': 'Game created',
            'game': game.id
        }
        return jsonify(response), 201
    except Exception as e:
        print('error')
        print(e)
        print(e.__dict__)
        response = {
            'status': 'fail',
            'message': 'There was an error. Please try again.'
        }
        return jsonify(response), 401
Ejemplo n.º 3
0
    def on_client_connect(self, websocket, path):
        logging.debug("New connection from: {}".format(
            websocket.remote_address))

        id = hash("{}{}".format(websocket.remote_address,
                                datetime.datetime.utcnow().isoformat()))
        client = Client(id, websocket)

        if len(self.pending_clients) == (Game.NUM_CLIENTS_TO_GAME - 1):
            # start the game
            logging.debug("Start the new game")
            players = [client] + self.pending_clients
            self.pending_clients = []
            asyncio.ensure_future(Game(players, self.loop).start(),
                                  loop=self.loop)
            logging.debug("New game session was started")
        else:
            self.pending_clients.append(client)

        try:
            yield from websocket.send(greeting(id))

            while True:
                message = yield from websocket.recv()
                logging.debug("Client({}) sent an request: {}".format(
                    id, message))
                client.received_command(message)
        except websockets.ConnectionClosed:
            logging.debug("Client({}) disconnected".format(id))
            if client in self.pending_clients:
                self.pending_clients.remove(client)
Ejemplo n.º 4
0
    def _GetAllGames(self, all_game_lists):
        index = 'A'
        games_list = []
        for item in all_game_lists:
            team_vs = GetOneElementByClass(item, 'div', 'team_vs')
            team_details_div = GetElementsByClass(team_vs, 'div', 'txt')

            team_score_a = GetOneElementByClass(
                team_details_div[0], 'span', 'num')
            team_score_b = GetOneElementByClass(
                team_details_div[1], 'span', 'num')

            team_score_a = GetTextOfItem(team_score_a, '0')
            team_score_b = GetTextOfItem(team_score_b, '0')

            team_name_a = GetTextOfItem(team_details_div[0].find('a'))
            team_name_b = GetTextOfItem(team_details_div[1].find('a'))

            team_a = Team(name=team_name_a, score=team_score_a)
            team_b = Team(name=team_name_b, score=team_score_b)

            team_vs_time = GetOneElementByClass(team_vs, 'span', 'b')
            team_vs_time = GetTextOfItem(team_vs_time, '      未开始')

            games_list.append(Game(index, team_a, team_b, team_vs_time))

            index = chr(ord(index) + 1)
        return games_list
Ejemplo n.º 5
0
def main():
    while True:
        print("Welcome to The Fun Game !!!\n")
        game = Game()
        game.rounds = 5
        print(
            "1. Single player (Player vs Bot)\n2. Double player (Player vs Player)\n"
            "3. Demo (KindBot vs Evil Bot)\n4. Exit")
        choice = input("Enter your option : ")
        if choice in ["1", "2", "3"]:
            game.initialize(int(choice))

        elif choice == "4":
            exit()
        else:
            print("Enter a valid option")
Ejemplo n.º 6
0
    def __init__(self, parent):
        super().__init__()
        self._game = Game()
        self._history = History()
        self._game_view = GameView()
        self._status_view = StatusView()
        self._history_view = HistoryView()

        parent.setCentralWidget(self._game_view)
        parent.addDockWidget(Qt.TopDockWidgetArea, self._status_view)
        parent.addDockWidget(Qt.RightDockWidgetArea, self._history_view)

        # Make Connections
        for row in self._game_view.squares:
            for square in row:
                # TODO: Look into why a lambda function is necessary; the method itself doesn't work
                square.clicked.connect(
                    lambda coords: self.handle_square_click(coords))

        # Set up the initial state of the board
        self._game_view.update_squares(self._game.board)
        message = self.create_status_message("")
        self._status_view.update_message(message)
Ejemplo n.º 7
0
import threading
import time

import PySimpleGUI as sg

from file.MoveReader import MoveReader
from file.MoveWriter import MoveWriter
from models.AI import AILvl1, AILvl2, AILvl3
from models.Builder import Builder
from models.Game import Game

# Get new Game instance
game = Game()
# Initialize MoveWriter (set (default) writing location)
MoveWriter.init()

# Set PySimpleGUI theme -> Dark or Light + Color + Number
sg.change_look_and_feel('DarkBlack1')

# Wait after move
wait = 0.5

# Depth for MiniMax algorithm
depth = 3

# Play-by-play between two bots
play_by_play = False

# Main Menu ======================================================================================
# Make main menu layout
menu_layout = [  #matrica sa svim izborima
Ejemplo n.º 8
0
def main():
    game = Game()
    game.init()
    while True:
        game.update()
Ejemplo n.º 9
0
parser.add_argument("--port",
                    "-P",
                    help="Server port to connect to",
                    type=int,
                    default=5555)
parser.add_argument("--heuristic",
                    help="Which heuristic to use",
                    type=str,
                    default="monogroup")
args = parser.parse_args()

if __name__ == "__main__":
    try:
        assert args.heuristic in HEURISTICS

        game = Game(args.host, args.port, args.name)
        print("// You are playing {}".format(game.type))
        turn = 0
        while game.is_running:
            game.update_map()
            sleep(1)
            if game.is_running:
                turn += 1
                moves = alphabeta_search(game.type,
                                         game.get_map(),
                                         d=4,
                                         heuristic_played=args.heuristic)

                try:
                    game.send_move(moves)
                except ValueError as exception:
Ejemplo n.º 10
0
def create_game():
    data = request.get_json()
    game = Game(**data).save()
    return Response(game.to_json(), mimetype="application/json", status=200)