Beispiel #1
0
def enter():
    global scoreLabel
    global networkLabel
    global opScoreLabel
    xs = [200, 400, 600]
    ids = [{'score': 100}, {'score': 10}, {'score': 1}]
    for i in range(len(xs)):
        btn = ui.Button('check', xs[i], 500, onClick, ids[i])
        ui.buttons.append(btn)

    btn = ui.Button('check', 700, 100, onClick, {'connect': True})
    ui.buttons.append(btn)

    label = ui.Label("Hello world", 100, 200, 50, ui.FONT_1)
    ui.labels.append(label)
    label = ui.Label("Same font", 100, 250, 50, ui.FONT_1)
    label.color = (0, 127, 0)
    ui.labels.append(label)

    label = ui.Label("Quick brown fox scores 210,000", 100, 100, 20, ui.FONT_2)
    ui.labels.append(label)
    networkLabel = label

    label = ui.Label("Other color", 100, 400, 50, ui.FONT_2)
    label.color = (127, 127, 255)
    ui.labels.append(label)
    scoreLabel = label

    label = ui.Label("Other color", 100, 350, 50, ui.FONT_2)
    label.color = (255, 127, 127)
    ui.labels.append(label)
    opScoreLabel = label
    global sess
    sess = GameSession(onOpponentMsg)
def create_game_sessions():

    form = request.get_json()
    print form
    if form is None:
        return api_error("Invalid Request")

    schema = {
                'name':{'type':'string','empty':False},
                'game_id':{'type':'integer','required':True},
                'start_date':{'type':'string','empty':False},
                'host_is_playing':{'type':'boolean','required':True}
            }
    v = Validator(schema)
    if v.validate(form) is False:
        return api_validation_error(v.errors)    

    game = Game().query.filter_by(game_id=form['game_id']).first()
    if game is None:
        return api_error("There was an issue adding the game to this session.") #this probably shouldnt happen but, we should check anyways

    newgamesession = GameSession()
    user = current_user._get_current_object()

    if form['host_is_playing'] is True:
        newgamesession.players.append(user) #the user/host is also a player.
        addplayer_helper(newgamesession,user)

    newgamesession.host = user #attach this session to the user creating it, as they are the host.

    newgamesession.game = game #relate this gamesession to this board game

    #name is optional. If left empty, the board games name will be used instead.
    if 'name' in form:
        newgamesession.name = form['name']
    else:
        newgamesession.name = game.name

    #user can specify a future start date, otherwise utcnow() is used as default value in table.
    if 'start_date' in form:
        newgamesession.start_date = date_parse(form['start_date'])

    meeple.db.session.add(newgamesession)
    meeple.db.session.commit()
    return api_package(data=newgamesession.as_dict())
Beispiel #3
0
def generate_game_sessions_with_all_parameters():
    path = _create_path(dir='virtual_players')
    make_directory(directory=path)
    params_ql, params_rl = prepare_params()
    for trial in params_ql:
        game = GameSession()
        model = Qlearning()
        player = VirtualPlayer(trial[0],
                               trial[1],
                               game_skeleton=game.game_skeleton,
                               model=model)
        game.play(player=player)
        file = tuple(map(str, round_number(trial[0]), round_number(trial[1])))
        path = _create_file_path(filename="QL_" + "_".join(file))
        game.save_results(path)
Beispiel #4
0
def generate_game_sessions_with_real_player_parameters():
    path = _create_path(dir='virtual_players')
    make_directory(directory=path)
    df = pd.read_csv('/Users/karola/PycharmProjects/ZPI/data/RW_RP_params.csv')
    for index, row in df.iterrows():
        game = GameSession()
        model = RescorlaWagner()
        player = VirtualPlayer(row['T'],
                               row['alpha_gain'],
                               row['alpha_lose'],
                               game_skeleton=game.game_skeleton,
                               model=model)
        game.play(player=player)
        file = tuple(
            map(str, (round_number(row['T']), round_number(row['alpha_gain']),
                      round_number(row['alpha_lose']), row['name'])))
        path = _create_file_path(filename="RW_" + "_".join(file))
        game.save_results(path)
Beispiel #5
0
    def _listen_api(self, connection):
        begin = time()

        # while time() - begin < 200:
        while time() - begin < 2:
            data = self._receive_dict_async(connection)
            if data and 'action' in data:
                if data['action'] == 'create_session':
                    new_session = GameSession(deck_cards=data['deck_cards'],
                                              attributes=data['attributes'])
                    start_new_thread(new_session.session_loop, ())
                    self.game_sessions.append(new_session)
                    self._send_dict(connection, {'session_id': new_session.id})
                    break

                elif data[
                        'action'] == 'destroy_session' and 'session_id' in data:
                    for idx, session in enumerate(self.game_sessions):
                        if session.id == data['session_id']:

                            self.game_sessions[idx].active = False
                            self._send_dict(connection, {'deleted': True})
                            break

                    self._send_dict(connection, {'deleted': False})
                elif data['action'] == 'get_sessions':
                    session_data = []
                    for session in self.game_sessions:
                        if session.active:
                            session_data.append(session.serialize())
                    self._send_dict(connection, session_data)
                    logging.info('API requested session list')
                    break

        connection.close()
        logging.info('API disconnected')
Beispiel #6
0
 def set_session(self):
     self.session = GameSession(self.id)
Beispiel #7
0
class Player(object):
    def __init__(self, id, name=None, email=None, password=None):
        self.id = id
        self.name = name
        self.email = email
        self.password = password
        self.created = datetime.datetime.now()
        self.updated = self.created
        self.money = MoneyPlayer(player_id=self.id)
        self.counters = CountersPlayer(player_id=self.id)
        self.achievements = PlayerAchievements(player_id=self.id)

    def as_dict(self):
        d = {
            'name_class': self.__class__.__name__,
            'id': self.id,
            'name': self.name,
            'email': self.email,
            'password': self.password,
            'created': self.created,
            'updated': self.updated
        }
        return d

    def save_to_db(self):
        cursor = db.connect.cursor()
        sql_data = self.as_dict()
        insert_query = 'insert into player (id, name, email, password, created, updated)' \
            ' values (%(id)s, %(name)s, %(email)s, %(password)s, %(created)s, %(updated)s)'
        update_query = 'update player ' \
            'set name=%(name)s, email=%(email)s, password=%(password)s, updated=%(updated)s ' \
            'where id=%(id)s'
        try:
            cursor.execute(insert_query, sql_data)
        except db.IntegrityError:
            sql_data['updated'] = datetime.datetime.now()
            cursor.execute(update_query, sql_data)
        db.connect.commit()

    def delete_from_db(self):
        cursor = db.connect.cursor()
        delete_query = 'delete from player where id=%(id)s'

        sql_data = {
            'id': self.id
        }
        try:
            cursor.execute(delete_query, sql_data)
        except:
            print('error delete player')

    def load_from_db(self, email):
        load_query = 'select id, name, email, password, created, updated ' \
                     'from player' \
                     ' where email=%(email)s'
        sql_data = {
            'email': email
        }
        cursor = db.connect.cursor()
        try:
            cursor.execute(load_query, sql_data)
            db_row = cursor.fetchone()
            self.id = db_row[0]
            self.name = db_row[1]
            self.email = db_row[2]
            self.password = db_row[3]
            self.created = db_row[4]
            self.updated = db_row[5]
        except TypeError:
            print('error load player')

    def save(self, file_object):
        json.dump(self.as_dict(), file_object)

    def load(self, file_object):
        object_as_dict = json.load(file_object)
        self.id = object_as_dict['id']
        self.name = object_as_dict['name']
        self.email = object_as_dict['email']
        self.password = object_as_dict['password']
        self.created = object_as_dict['created']
        self.updated = object_as_dict['updated']

    def get_money_player(self):
        return self.money.load_from_db(self.id)

    def delete_money_player(self):
        self.money.delete_from_db()

    def set_session(self):
        self.session = GameSession(self.id)

    def leave_the_game(self):
        self.session.save_to_db()
        self.money.save_to_db()
        self.counters.save_to_db()
        self.achievements.save_to_db()

    def get_counters_player(self):
        return self.counters.load_from_db(self.id)

    def delete_counters_player(self):
        self.counters.delete_from_db()

    def get_achievements_player(self):
        return self.achievements.load_from_db(self.id)

    def delete_achievemets_player(self):
        self.achievements.delete_from_db()

    def __str__(self):
        return '{}(id={}, name="{}", email="{}", password="******", created={}, updated={})'.format(
            self.__class__.__name__,
            self.id,
            self.name,
            self.email,
            self.password,
            self.created,
            self.updated
        )
Beispiel #8
0
 def set_session(self):
     self.session = GameSession(self.id)
Beispiel #9
0
class Player(object):
    def __init__(self, id, name=None, email=None, password=None):
        self.id = id
        self.name = name
        self.email = email
        self.password = password
        self.created = datetime.datetime.now()
        self.updated = self.created
        self.money = MoneyPlayer(player_id=self.id)
        self.counters = CountersPlayer(player_id=self.id)
        self.achievements = PlayerAchievements(player_id=self.id)

    def as_dict(self):
        d = {
            'name_class': self.__class__.__name__,
            'id': self.id,
            'name': self.name,
            'email': self.email,
            'password': self.password,
            'created': self.created,
            'updated': self.updated
        }
        return d

    def save_to_db(self):
        cursor = db.connect.cursor()
        sql_data = self.as_dict()
        insert_query = 'insert into player (id, name, email, password, created, updated)' \
            ' values (%(id)s, %(name)s, %(email)s, %(password)s, %(created)s, %(updated)s)'
        update_query = 'update player ' \
            'set name=%(name)s, email=%(email)s, password=%(password)s, updated=%(updated)s ' \
            'where id=%(id)s'
        try:
            cursor.execute(insert_query, sql_data)
        except db.IntegrityError:
            sql_data['updated'] = datetime.datetime.now()
            cursor.execute(update_query, sql_data)
        db.connect.commit()

    def delete_from_db(self):
        cursor = db.connect.cursor()
        delete_query = 'delete from player where id=%(id)s'

        sql_data = {'id': self.id}
        try:
            cursor.execute(delete_query, sql_data)
        except:
            print('error delete player')

    def load_from_db(self, email):
        load_query = 'select id, name, email, password, created, updated ' \
                     'from player' \
                     ' where email=%(email)s'
        sql_data = {'email': email}
        cursor = db.connect.cursor()
        try:
            cursor.execute(load_query, sql_data)
            db_row = cursor.fetchone()
            self.id = db_row[0]
            self.name = db_row[1]
            self.email = db_row[2]
            self.password = db_row[3]
            self.created = db_row[4]
            self.updated = db_row[5]
        except TypeError:
            print('error load player')

    def save(self, file_object):
        json.dump(self.as_dict(), file_object)

    def load(self, file_object):
        object_as_dict = json.load(file_object)
        self.id = object_as_dict['id']
        self.name = object_as_dict['name']
        self.email = object_as_dict['email']
        self.password = object_as_dict['password']
        self.created = object_as_dict['created']
        self.updated = object_as_dict['updated']

    def get_money_player(self):
        return self.money.load_from_db(self.id)

    def delete_money_player(self):
        self.money.delete_from_db()

    def set_session(self):
        self.session = GameSession(self.id)

    def leave_the_game(self):
        self.session.save_to_db()
        self.money.save_to_db()
        self.counters.save_to_db()
        self.achievements.save_to_db()

    def get_counters_player(self):
        return self.counters.load_from_db(self.id)

    def delete_counters_player(self):
        self.counters.delete_from_db()

    def get_achievements_player(self):
        return self.achievements.load_from_db(self.id)

    def delete_achievemets_player(self):
        self.achievements.delete_from_db()

    def __str__(self):
        return '{}(id={}, name="{}", email="{}", password="******", created={}, updated={})'.format(
            self.__class__.__name__, self.id, self.name, self.email,
            self.password, self.created, self.updated)
Beispiel #10
0
from player import Player
from player_command import RaiseCommand, FoldCommand, CallCommand, CheckCommand, NextGameCommand
from player_manager import PlayerManager
from game_session import GameSession

app = Flask(__name__)
config.load_config(app)
player_names = ["alfred", "betty", "chris", "dee"]
players = [
    Player(handle=name, hand=Hand([]), id=uuid.uuid4())
    for name in player_names
]
player_manager = PlayerManager(players)
print(players)
game = Game(players, Deck(), little_ante=10, big_ante=20)
game_session = GameSession(game=game)

command_evaluator = CommandEvaluator(game_session)
game_session.current_round.deal_cards_1_2()

service = game_session.current_round
app.secret_key = config.SECRET


@app.route("/god_mode")
def friendly_god_game_view():
    return render_template('root_template.html', session=game_session)


@app.route("/")
def player_view():
Beispiel #11
0
from settings import Settings
from game_session import GameSession
from text_color import *
settings = Settings()
session = GameSession("dsa-355", 1, settings)


def print_boards(session):
    print("Your board:            Enemy board:")
    rows = len(session.player_board)
    cols = len(session.player_board[0])
    for row in range(rows):
        print(str(chr(row + 65)), end=" ")
        for col in range(cols):
            grid = session.player_board[row][col]
            if session.player_board_hit_grid[row][col]:
                change_text_color("Red")
            if grid:
                print(session.player_board[row][col], end=" ")
            else:
                print(".", end=" ")
            change_text_color("Default")
        print("    ", end=" ")
        print(str(chr(row + 65)), end=" ")
        for col in range(cols):
            grid = session.enemy_board[row][col]
            if session.enemy_board_hit_grid[row][col]:
                change_text_color("Red")
            if grid:
                print(session.enemy_board[row][col], end=" ")
            else: