示例#1
0
    def new_game(cls, request):
        """Creates and returns a new game"""
        gplus_user = get_endpoints_current_user()
        user = User.query(User.email == gplus_user.email()).get()

        if request.total_rounds not in ROUNDS_OPTIONS:
            raise endpoints.BadRequestException('Invalid total number of rounds.'
                                                ' Must be a number contained in the set: {0}.'.format(ROUNDS_OPTIONS))

        game = Game(user=user.key, total_rounds=request.total_rounds, remaining_rounds=request.total_rounds)
        game.put()
        return game.to_form()
示例#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
示例#3
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
示例#4
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)
示例#5
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
示例#6
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")
示例#7
0
    def get_user_games(cls):
        """Returns all of the current User's active games"""
        gplus_user = get_endpoints_current_user()
        user = User.query(User.email == gplus_user.email()).get()

        active_games = Game.query() \
            .filter(Game.user == user.key) \
            .filter(Game.game_over == False)
        return GameForms(games=[game.to_form() for game in active_games])
示例#8
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)
示例#9
0
    def get(self):
        """Send a reminder email to each User with incomplete active games.
        Called every 24 hours using a cron job"""
        app_id = app_identity.get_application_id()
        games = Game.query(Game.game_over == False)
        users = []

        for game in games:
            user = game.user.get()
            if user not in users:  # Limit emails to 1 per user per day
                users.append(user)

        for user in users:
            subject = 'This is a reminder!'
            body = 'Hello {}, come back and finish your game of Rock, Paper, Scissors!'.format(user.displayName)
            mail.send_mail('noreply@{}.appspotmail.com'.format(app_id),
                           user.email,
                           subject,
                           body)
示例#10
0
from models.Game import Game

if __name__ == '__main__':
    game = Game()
    game.start_game()
示例#11
0
文件: main.py 项目: vinhvu200/2048_RL
import random
import time

from models.enum.direction import Direction
from models.Game import Game
from models.q_learn import Q_Learn
from sklearn.preprocessing import StandardScaler

game = Game()
game.update()
game.highest = game.highest_tile()


def play():
    while (game.game_over() is False):

        r = random.randint(1, 4)

        if r is 1:
            next_state, _, _, _ = game.move(Direction.RIGHT)
        if r is 2:
            next_state, _, _, _ = game.move(Direction.LEFT)
        if r is 3:
            next_state, _, _, _ = game.move(Direction.DOWN)
        if r is 4:
            next_state, _, _, _ = game.move(Direction.UP)
    #game.replay()


def manual():
    while game.game_over() is False:
示例#12
0
文件: main.py 项目: Dramelac/AwaleAI
from models.Game import Game

if __name__ == '__main__':
    game = Game()
    game.start()

示例#13
0
def main():
    game = Game()
    game.init()
    while True:
        game.update()
示例#14
0
def create_game():
    data = request.get_json()
    game = Game(**data).save()
    return Response(game.to_json(), mimetype="application/json", status=200)
示例#15
0
""" application/__init__.py
"""

from flask import Flask
from flask_socketio import SocketIO
from os import urandom

app = Flask(__name__)
app.debug = True
app.secret_key = urandom(24)
socketio = SocketIO(app)

from models.Game import Game
game = Game()

import application.comm, application.views
示例#16
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:
示例#17
0
class GameController(QObject):
    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)

    @Slot(tuple)
    def handle_square_click(self, coords):
        """ Validates a piece selection; updates the Board. """
        if self.is_complete():
            message = self.create_status_message("")
            self._status_view.update_message(message)
            return

        source = self._game.board.selected

        # Catch gutter selections
        try:
            target = self.get_piece(coords)
        except IllegalMove as e:
            message = self.create_status_message(str(e))
            self._status_view.update_message(message)
            return

        # Deselection
        if source == target:
            self._game.board.selected = None
            self._game_view.update_selection(None)
            return

        # Selection
        if source is None:
            try:
                self.select_piece(target)
            except IllegalMove as e:
                message = self.create_status_message(str(e))
                self._status_view.update_message(message)
            finally:
                return

        # Make move
        try:
            self._game.make_move(source, target)
        except IllegalMove as e:
            message = self.create_status_message(str(e))
            self._status_view.update_message(message)
            return

        message = self.create_status_message("")
        self._status_view.update_message(message)

        self._game_view.update_squares(self._game.board)

        # Update history
        self._history.add_move(source, target)
        origin_center, destination_center = self._history.get_last_move()
        self._history_view.add_move(origin_center, destination_center)

    def select_piece(self, target):
        """ Selects a 3x3 piece to be moved. """
        if self.is_piece_empty(target):
            raise IllegalMove("This piece has no stones.")

        if not self.is_player_piece(target):
            raise IllegalMove("This piece is not the active player's.")

        self._game.board.selected = target
        self._game_view.update_selection(target)

    def get_piece(self, center):
        """ Accepts center coordinates (row, col) for a piece and returns it
            as a dictionary in the form {(row, col): stone}. """
        try:
            # Prevents index wraparound
            if 0 in center:
                raise IndexError

            piece = {}
            squares = self._game.board.squares

            for row, col in product(range(-1, 2), range(-1, 2)):
                coords = center[0] + row, center[1] + col
                piece[coords[0], coords[1]] = squares[coords[0]][coords[1]]
        except IndexError:
            raise IllegalMove("Cannot select from the gutter.")

        return piece

    def is_player_piece(self, piece):
        """ Returns True if the given piece belongs solely to the active player. """
        player_stone = self._game.active_player.stone
        stone_set = set(piece.values()) - {""}

        return stone_set == set(player_stone)

    def is_complete(self):
        """ Returns true if the game has been won. """
        return self._game.game_state != "UNFINISHED"

    def create_status_message(self, status_message):
        """ Creates a message from the model's state for the status view. """
        message = ""
        if self._game.game_state == "UNFINISHED":
            message += "{}'s turn".format(
                self._game.active_player.color.title())

            if status_message:
                message += "; "
        else:
            message += self._game.game_state.replace("_", " ").title()

        return message + status_message

    @staticmethod
    def is_piece_empty(piece):
        """ Returns true if a 3x3 piece contains no stones. """
        for stone in piece.values():
            if stone:
                return False

        return True
示例#18
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
示例#19
0
def get_games():
    games = Game.objects().to_json()
    return Response(games, mimetype="application/json", status=200)