Пример #1
0
def create_room(request):
    now = datetime.now()
    time = now.strftime("%H:%M:%S")
    hash = hashlib.md5((time + request.user.username).encode())
    room = Room(user_1_id=request.user.id, hash=hash.hexdigest())
    room.save()
    return redirect('game', room.hash)
Пример #2
0
def create_room(nickname):
    room = Room(code=generate_room_code(), state=Room.WAITING)
    room.save()
    user = User(room=room,
                nickname=nickname,
                is_owner=True,
                unique_id=uuid.uuid4().__str__())
    user.save()
    return CreateRoomResult(room, user)
Пример #3
0
def create(data):

    if Room.objects.filter(opened=True).first():
        raise Exception('Only ONE room can be opened at once.')

    t_max = int(data["t_max"])
    training_t_max = int(data["training_t_max"])

    count_type = [int(v) for k, v in data.items() if k.startswith("x")]
    n_user = sum(count_type)
    n_type = len(count_type)

    types = [i for i in range(n_type) for _ in range(count_type[i])]

    rm = Room(t_max=t_max,
              training_t_max=training_t_max,
              t=0,
              training_t=0,
              state=game.room.state.states.WELCOME,
              opened=True,
              n_user=n_user,
              n_type=n_type,
              types="/".join([str(i) for i in count_type]))

    rm.save()

    Choice.objects.bulk_create([
        Choice(
            room_id=rm.id,
            t=t,
            player_id=n,
            user_id=None,
            good_in_hand=types[n] if not t else None,
            desired_good=None,
            success=None,
        ) for n in range(n_user) for t in range(t_max)
    ])

    TutorialChoice.objects.bulk_create([
        TutorialChoice(room_id=rm.id,
                       t=t,
                       player_id=n,
                       user_id=None,
                       good_in_hand=types[n] if not t else None,
                       desired_good=None,
                       success=None) for n in range(n_user)
        for t in range(training_t_max)
    ])

    return rm
Пример #4
0
def host_game(request, game_code):
    user = request.user
    game = Game.objects.get(code=game_code)
    if not Room.objects.can_create_room(user=user):
        messages.add_message(
            request,
            messages.INFO,
            "You have created maximum rooms. Please exit from there to create new room",
        )
        return redirect("home")
    room = Room(game=game, created_by=user)
    room.max_members = game.max_player
    room.save()
    return redirect("host_room", sp_id=room.sp_id)
Пример #5
0
def test_room_completed(cards):
    r = Room(cards)
    r.select_card('j')
    r.select_card('k')
    r.select_card('l')
    r.select_card(';')
    assert r.completed() == True
Пример #6
0
def add_room(request):
    if request.method == 'POST':
        if 'roomName' not in request.POST:
            error = {'error': 'Missing required fields'}
            return HttpResponse(json.dumps(error), content_type='application/json')
        roomName = request.POST['roomName']
        if Room.objects.filter(name__exact=roomName).exists():
            error = {'error': 'Duplicate room name!'}
            return HttpResponse(json.dumps(error), content_type='application/json')
        gameRoom = Room(name=roomName, host=request.user)
        gameRoom.save()

        room_item = {
            'id': gameRoom.id,
            'roomName': gameRoom.name,
            'host': request.user.username,
            'playerNum': 1
        }
        return HttpResponse(json.dumps(room_item), content_type='application/json')
Пример #7
0
    def create_room(sid, name):
        from game.models import Room
        from authorization.models import User

        session = io.get_session(sid)
        code = generate_random_string()
        socket_id = "game-{}".format(code)
        room = Room.objects.create(name=name, socket_id=socket_id)
        User.objects.filter(pk=session["id"]).update(room=room,
                                                     is_room_admin=True)
        io.emit(EVENTS_EMIT["CREATED_ROOM"], Room.serialize(room))

        return socket_id
Пример #8
0
def create(data):

    is_trial = int(bool(data['trial']))
    ending_t = int(data["ending_t"])
    radius = data['radius']
    nb_of_room = int(data["nb_of_room"])

    missing_players = 1 if is_trial else 2

    for r in range(nb_of_room):

        # get room_id: if already exists, increment
        # until it doesnt found an existing record
        room_id = 1

        while True:

            if Room.objects.filter(room_id=room_id).first() is None:
                break

            else:
                room_id += 1

        round.dialog.create_rounds(room_id=room_id,
                                   ending_t=ending_t,
                                   trial=is_trial,
                                   called_from=__path__ + "." + utils.fname())

        rm = Room(state=state.tutorial,
                  ending_t=ending_t,
                  radius=radius,
                  player_0=_generate_unique_player_id(),
                  player_1=_generate_unique_player_id(),
                  trial=is_trial,
                  missing_players=missing_players,
                  room_id=room_id,
                  opened=1)

        rm.save()
Пример #9
0
 def add_room(self, room_name):
     """Create a room entry in database.
     Returns True if successful, False otherwise"""
     try:
         new_room = Room(name=room_name,
                         password="",
                         num_players=1,
                         game_started=False)
         new_room.save()
     except IntegrityError as ex:
         if "UNIQUE constraint failed" in ex.args[0]:
             logging.info(
                 f"Room {room_name} already exist in database. No new entry added."
             )
         else:
             logging.error(
                 f"Error occured while trying to create new room: {ex}")
         return False
     except Exception as ex:
         logging.error(
             f"Error occured while trying to create new room: {ex}")
         return False
     return True
Пример #10
0
def create():
    form = CreateGame()
    if form.validate_on_submit():
        print(form.errors)
        noguess = form.guess_num.data
        username = form.username.data
        timeRem = form.timerem.data

        roomCode = genRoomCode()
        roomInst = Room(room_code=roomCode,
                        num_teams=2,
                        scorecard=False,
                        full_time=timeRem,
                        time_remaining=timeRem,
                        names_per=noguess,
                        roundNo=0,
                        ct=0,
                        timer_started=0,
                        game_started=0)
        db.session.add(roomInst)
        db.session.commit()
        room = Room.query.filter_by(room_code=roomCode).first()

        client = User(username=username,
                      room_id=room.id,
                      team=0,
                      play_order=0,
                      in_play=0)
        db.session.add(client)
        db.session.commit()

        user = User.query.filter_by(username=username, room_id=room.id).first()
        # getColours(form.teams_num.data)       # WILL ADD AT LATER DATE

        # Sets Cookie for User
        resp = make_response(redirect(url_for('addnames', roomCode=roomCode)))
        resp.set_cookie('user_id', str(user.id))
        return resp

    return render_template('create.html',
                           legend='Create a New Game',
                           form=form)
Пример #11
0
    def generate_rooms(self, size_x, size_y, num_rooms):
        self.grid = [None] * size_y
        self.width = size_x
        self.height = size_y
        for i in range(len(self.grid)):
            self.grid[i] = [None] * size_x

        reverse_dirs = {"n": "s", "s": "n", "e": "w", "w": "e", "err": "err"}

        x = -1
        y = 0
        room_count = 0

        direction = 1

        previous_room = None
        while room_count < num_rooms:
            print(
                f'direction:{direction}, room count:{room_count}, x:{x}, y:{y}'
            )
            if direction > 0 and x < size_x - 1:
                room_direction = "e"
                x += 1
            elif direction < 0 and x > 0:
                room_direction = "w"
                x -= 1
            else:
                room_direction = "n"
                y += 1
                direction *= -1

            room = Room(room_count, "A Generic Room",
                        "This is a generic room.", x, y)
            print(room)
            room.save()
            self.grid[y][x] = room

            if previous_room is not None:
                previous_room.connect_rooms(room, room_direction)
                room.connect_rooms(previous_room, reverse_dirs[room_direction])

            previous_room = room
            room_count += 1
Пример #12
0
 def get_rooms(sid):
     from game.models import Room
     return Room.serialize_many(
         Room.objects.annotate(users_count=Count("users")).filter(
             users_count__lte=3))
Пример #13
0
def test_room_select_card(cards):
    r = Room(cards, player_escaped_previous_room=True)
    card = r.select_card('k')
    assert card.suit == SPADE
    assert card.value == 2
Пример #14
0
def test_room_flee_failure(cards):
    r = Room(cards, player_escaped_previous_room=True)
    assert r.flee() == None
Пример #15
0
def test_room_flee_success(cards):
    r = Room(cards)
    assert set(r.flee()) == set(cards)
Пример #16
0
def home_view(request):
    username = request.session.get('username')
    print(username)
    if request.method == "POST":
        room_event = request.POST.get('event')
        room_code = request.POST.get('room_code')
        room_size = request.POST.get('room_size')
        print(room_code)
        print(room_event)
        if room_event == "Create":
            existing_room = Room.objects.filter(room_code=room_code)
            if len(existing_room) == 0:
                print(f"Room : {room_code}Created Successfully")
                room = Room(room_code=room_code,
                            room_host=username,
                            room_size=room_size)
                room.save()
                roomlobby = RoomLobby(room=room,
                                      room_code=room_code,
                                      room_user=username,
                                      score=0,
                                      is_online=False,
                                      user_id=0)
                roomlobby.save()
                return redirect('/game/play/' + room_code)
            else:
                print("Room code already existed!! Create a new one.")
                messages.success(
                    request, "Room code already existed!! Create a new one.")
        elif room_event == "Join":
            existing_room = Room.objects.filter(room_code=room_code)
            if len(existing_room) == 0:
                print(f"No such room_code : {room_code} exists!!")
                messages.success(request, "No such room_code exists!!")
            elif existing_room[0].game_started == True:
                messages.success(
                    request,
                    "Game has been started!! You can't join in between!!")
            else:
                room_user_existed = RoomLobby.objects.filter(
                    room_code=room_code, room_user=username)
                if len(room_user_existed) == 0:
                    room_users = RoomLobby.objects.filter(room_code=room_code)
                    room_size = Room.objects.filter(
                        room_code=room_code)[0].room_size
                    if len(room_users) < room_size:
                        roomlobby = RoomLobby(room=existing_room[0],
                                              room_code=room_code,
                                              room_user=username,
                                              score=0,
                                              is_online=False,
                                              user_id=len(room_users))
                        roomlobby.save()
                        print(f"Room : {room_code} joined successfully!")
                        return redirect('/game/play/' + room_code)
                    else:
                        messages.success(request,
                                         "room is full!! Join another room.")
                        print("room is full!! Join another room.")
                else:
                    print(f"Room : {room_code} joined successfully!")
                    return redirect('/game/play/' + room_code)

    context = {'username': username}
    return render(request, 'home.html', context)
Пример #17
0
def test_room_not_completed(cards):
    r = Room(cards)
    r.select_card(';')
    assert r.completed() == False
Пример #18
0
def test_room_previous_escaped(cards):
    r = Room(cards, player_escaped_previous_room=True)
    assert r.escapable() == False
    r.select_card('k')
    r.select_card('l')
    assert r.escapable() == True
Пример #19
0
    def connect(self):
        '''
        This function is called when a websocket connection request is sent from browser
        '''

        self.hostReady = False
        self.playerReady = False

        '''parse game room name'''
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = self.room_name
        '''parse current user'''
        self.user = self.scope['user']

        '''Join room group'''
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )
        '''get current room from database'''
        current_room = Room.objects.filter(name=self.room_group_name).first()
        if not current_room:
            '''create one if not exists'''
            current_room = Room(name=self.room_group_name, host=None, player=None, num_player=0)
            '''initialize game start status to false'''
            game_room_start_status[self.room_group_name] = False
            '''initialize game ready-user to empty dictionary'''
            game_room_ready_user[self.room_group_name] = {}
            '''initialize game ready-to-show-user to empty dictionary'''
            game_room_end_user[self.room_group_name] = {}
            '''initialize game used cards to empty dictionary'''
            game_room_used_cards[self.room_group_name] = {}
            game_room_used_cards[self.room_group_name]['all_cards'] = {}
            game_room_used_cards[self.room_group_name]['first_cards'] = {}
            # init reconnect states
            game_room_disconnected[self.room_group_name] = []
            game_room_lock[self.room_group_name] = threading.Lock()


        # add players
        game_room_lock[self.room_group_name].acquire()
        # if reconnect
        isReconnect = False
        if self.user.username in game_room_disconnected[self.room_group_name]:
            game_room_disconnected[self.room_group_name].remove(self.user.username)
            isReconnect = True
        else:  # new connection
            if current_room.num_player >= 1 and current_room.host == self.user \
                or current_room.num_player == 2 and current_room.player == self.user \
                or current_room.num_player >= 2:
                # reject dup connections or excessive players
                self.close()
            elif not hasattr(current_room, 'host'):
                current_room.host = self.user
                current_room.num_player += 1
                game_room_ready_user[self.room_group_name][self.user.username] = False
                game_room_end_user[self.room_group_name][self.user.username] = False
                # host draws first
                game_room_next[self.room_group_name] = self.user.username
                current_room.save()
            else:  # add player
                current_room.player = self.user
                current_room.num_player += 1
                game_room_ready_user[self.room_group_name][self.user.username] = False
                game_room_end_user[self.room_group_name][self.user.username] = False
                current_room.save()
        game_room_lock[self.room_group_name].release()
        self.accept()


        # broadcast player info
        hostMsg = {
            'username': current_room.host.username,
            'pid': current_room.host.my_profile.id,
            'score': current_room.host.my_profile.score,
            'win': current_room.host.my_profile.num_win,
            'lose': current_room.host.my_profile.num_lose,
            'ready': game_room_ready_user[self.room_group_name][current_room.host.username],
            'current_draw': game_room_next[self.room_group_name],
        }
        playersInfo = {
            'type': 'players_connect',
            current_room.host.username: hostMsg
        }
        if current_room.num_player == 2:
            playerMsg = {
                'username': current_room.player.username,
                'pid': current_room.player.my_profile.id,
                'score': current_room.player.my_profile.score,
                'win': current_room.player.my_profile.num_win,
                'lose': current_room.player.my_profile.num_lose,
                'ready': game_room_ready_user[self.room_group_name][current_room.player.username],
                'current_draw': game_room_next[self.room_group_name],

            }
            playersInfo[current_room.player.username] = playerMsg

        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            playersInfo
        )

        # retrieve game progress for reconnect
        user1, user2, user1_card, user2_card = get_all_cards(current_room.name)

        # send cards to front end
        for card in user1_card:
            user_card = {
                user1: card,
            }
            self.send(text_data=json.dumps({
                'card': user_card
            }))
        for card in user2_card:
            user_card = {
                user2: card,
            }
            self.send(text_data=json.dumps({
                'card': user_card
            }))
Пример #20
0
from game.models import Character, Room, Portal
from django.contrib.auth.models import User

# Users
u1 = User.objects.create_superuser(username='******', email='*****@*****.**', password='******') #Attention get_or_create
u2 = User.objects.create_user(username='******', password='******')

# Rooms
r1 = Room(name='1')
r1.save()
r2 = Room(name='2')
r2.save()
r3 = Room(name='3')
r3.save()

# Characters
c1 = Character(name='Conan', room=r1, user=u2, description='Le barbare')
c1.save()

# Portals
p1 = Portal(direction='N', entry=r1, exit=r2)
p1.save()
p2 = Portal(direction='E', entry=r2, exit=r3)
p2.save()
Пример #21
0
from django.contrib.auth.models import User
from game.models import Player, Room
from util.generate_world import World

Room.objects.all().delete()

r_outside = Room(title="Outside Cave Entrance",
                 description="North of you, the cave mount beckons")

r_foyer = Room(title="Foyer",
               description="""Dim light filters in from the south. Dusty
passages run north and east.""")

r_overlook = Room(title="Grand Overlook",
                  description="""A steep cliff appears before you, falling
into the darkness. Ahead to the north, a light flickers in
the distance, but there is no way across the chasm.""")

r_narrow = Room(title="Narrow Passage",
                description="""The narrow passage bends here from west
to north. The smell of gold permeates the air.""")

r_treasure = Room(title="Treasure Chamber",
                  description="""You've found the long-lost treasure
chamber! Sadly, it has already been completely emptied by
earlier adventurers. There are exits to the south and east.""")

r_parking_lot = Room(
    title="Empty Parking Lot",
    description=
    """North of you, an light flickers inside a telephone box. To the west is the empty treasure chamber."""
Пример #22
0
def test_room_escapable(cards):
    r = Room(cards, player_escaped_previous_room=False)
    assert r.escapable() == True