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)
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)
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)
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
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')
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
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()
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
description="""You've found the long-lost treasure chamber! Sadly, it has already been completely emptied by earlier adventurers. The only exit is to the south.""") r_alley = Room( title="The back of the kitchen", description= "You are standing in an alley-way beside several bags of rubbish. The air smells stale. North of you, the old kitchen beckons. You see a gate to the east." ) r_twelve = Room(title="Twelve", description="Another room") r_thirteen = Room(title="Thirteen", description="Another room") r_fourteen = Room(title="Fourteen", description="Another room") r_fifteen = Room(title="Fifteen", description="Another room") r_outside.save() r_foyer.save() r_overlook.save() r_narrow.save() r_treasure.save() r_parking_lot.save() r_telephone_box.save() r_swoosh.save() r_old_kitchen.save() r_alley.save() r_treasure_room.save() r_twelve.save() r_thirteen.save() r_fourteen.save() r_fifteen.save()
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)
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 }))
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()