def update_room_song(self, room: Room, song_id: int): current_song = room.current_song if current_song != song_id: room.current_song = song_id room.save(update_fields=['current_song']) votes = Vote.objects.filter(room=room).delete()
def post(self, request, format=None): if not self.request.session.exists(self.request.session.session_key): self.request.session.create() serializer = self.serializer_class(data=request.data) if serializer.is_valid(): guest_can_pause = serializer.data.get('guest_can_pause') votes_to_skip = serializer.data.get('votes_to_skip') host = self.request.session.session_key queryset = Room.objects.filter(host=host) if queryset.exists(): room: Room = queryset[0] room.guest_can_pause = guest_can_pause room.votes_to_skip = votes_to_skip room.save(update_fields=['guest_can_pause', 'votes_to_skip']) self.request.session['room_code'] = room.code return Response(RoomSerializer(room).data, status=status.HTTP_200_OK) else: room = Room(host=host, guest_can_pause=guest_can_pause, votes_to_skip=votes_to_skip) room.save() self.request.session['room_code'] = room.code return Response(RoomSerializer(room).data, status=status.HTTP_201_CREATED) return Response({'Bad Request': 'Invalid data...'}, status=status.HTTP_400_BAD_REQUEST)
def generate_rooms(self, size_x, size_y): self.grid = [None] * size_x self.width = size_x self.height = size_y for i in range(len(self.grid)): self.grid[i] = [None] * size_y idCount = 0 for x in range(size_x): for y in range(size_y): ranInt = random.randint(0, 9) if ranInt < 6: room = Room(idCount, "Road", "Just a dusty old road") idCount += 1 self.grid[x][y] = room room.positionx = x room.positiony = y room.save() else: ran = random.randint(0, 14) room = gen_room(ranInt=ran, roomId=idCount) idCount += 1 self.grid[x][y] = room room.positionx = x room.positiony = y room.save()
def post(self: View, request: HttpRequest) -> JsonResponse: """Create a user, provided the username.""" try: payload = json.loads(request.body.decode()) except json.JSONDecodeError: return error('You supplied incorrect data.') username = str(payload.get('username', '')) if request.session.get('registered'): return error('You are already registered.') if not 1 <= len(username) <= 100: return error('Username length must be between 1 and 100.') digest = uuid4().hex slug = humanize(digest) request.session['slug'] = slug request.session['registered'] = True request.session['username'] = username room = Room(uuid=digest, slug=slug) room.save() return JsonResponse({ 'success': True, 'slug': slug })
def move(request): user = Profile.objects.filter(user__username=request.user).first() headers = {'Authorization': f'Token {user.api_token}'} data = request.data response = requests.post(f'{BASE_URL}/move', headers=headers, json=data) response = response.json() res_tuple = eval(response['coordinates']) room = Room(id=response['room_id'], title=response['title'], description=response['description'], terrain=response['terrain'], elevation=response['elevation'], coordinates=res_tuple, x=res_tuple[0], y=res_tuple[1]) player = Player.objects.get(id=1) # connect room room.connectRooms(data['direction'], player.current_room, response['room_id']) # update room room.save() # update player player.current_room = response['room_id'] player.cooldown = response['cooldown'] player.save() return Response(response)
def post(self, request, room_number): request.session.save() json = JSONParser().parse(request) uuid = str(uuid4())[:6] token = str(uuid4())[:18] room = Room(title=json['title'], number=uuid, connected=0, token=token) room.save() request.session['room_admin_uuid'] = uuid return Response(RoomWithTokenSerializer(room).data, status=201)
def create_or_join_room(request): """ request.POST = { "room_code": "<>", "player_name": "<>" } """ if 'player_id' not in request.session: request.session['player_id'] = get_random_id() player_name = request.POST['player_name'] if not player_name: player_name = random.choice(animal_names) if Room.objects.filter(room_code=request.POST['room_code']).exists(): try: r = Room.objects.get(room_code=request.POST['room_code']) except Room.DoesNotExist: return HttpResponse(json.dumps({ "status": "error", "message": "Room does not exist." }, default=json_custom_parser), content_type='application/json', status=400) new_player = Player(**{ "room_code": r.room_code, "player_id": request.session['player_id'], "alias": player_name }) new_player.save() return HttpResponse(json.dumps({ "status": "success", "data": { "room_code": r.room_code, "player_name": player_name, "player_id": request.session['player_id'], "creator_player_id": r.creator_player_id, } }, default=json_custom_parser), content_type='application/json', status=200) else: Room.objects.filter(creator_player_id=request.session['player_id']).delete() new_room = Room(**{ "room_code": request.POST['room_code'], "creator_player_id": request.session['player_id'], }) new_room.save() new_player = Player(**{ "room_code": request.POST['room_code'], "player_id": request.session['player_id'], "alias": player_name }) new_player.save() return HttpResponse(json.dumps({ "status": "success", "data": { "room_code": new_room.room_code, "player_name": player_name, "player_id": request.session['player_id'], "creator_player_id": new_room.creator_player_id, } }, default=json_custom_parser), content_type='application/json', status=200)
# run this script in the django shell to create rooms # copy and paste in sections (separted by comments) from api.models import Room import json Room.objects.all().delete() room_data = json.load(open('util/rooms.json', 'r')) # create new rooms for room in room_data: r = room_data[room] new_room = Room(id=r['id']) new_room.title = r['title'] new_room.description = r['description'] new_room.x_coord = r['x_coord'] new_room.y_coord = r['y_coord'] new_room.elevation = r['elevation'] new_room.terrain = r['terrain'] new_room.save() # connect rooms together all_rooms = Room.objects.all() for room in all_rooms: for e in room_data[f"{room.id}"]['exits']: room.connect_rooms(room_data[f"{room.id}"]['exits'][e], e)
def generate_rooms(self, size_x, size_y, num_rooms): # Initialize the grid's height self.grid = [None] * size_y self.width = size_x self.height = size_y # fill the row up with an array of None for i in range(len(self.grid)): self.grid[i] = [None] * size_x # Start from lower-left corner (0,0) x = -1 # (this will become 0 on the first step) y = 0 # set to 1 so id can begin at 1 room_count = 1 # Start generating rooms to the east direction = 1 # 1: east, -1: west # While there are rooms to be created... previous_room = None # use to reverse the direction of the room reverse_dirs = {"n": "s", "s": "n", "e": "w", "w": "e", "err": "err"} # will be used to create chasm break_choices = [False, True, False, False, False] while room_count <= num_rooms: # Calculate the direction of the room to be created 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: # REMOVED THE NORTH SOUTH MAPPING AT THE ENDS OF THE MAP # # If we hit a wall, turn north and reverse direction # set the direction to something useless room_direction = "err" y += 1 direction *= -1 # THIS CREATES A CHASM IN THE EAST-WEST CONNECTION AT RANDOM POINTS # if 1 < y < (size_y - 3) if 1 < y < (size_y - 3): # randomize break_choices choice = random.choice(break_choices) # if true break the connection by setting the room direction to err if choice: room_direction = "err" # Create a room in the given direction room = Room( id=room_count, title=room_titles[room_count - 1], description= "The quest for thy nobly ring burns true and bright. Search on thou famed voyager!", x=x, y=y) # Note that in Django, you'll need to save the room after you create it room.save() # Save the room in the World grid self.grid[y][x] = room # Connect the new room to the previous room if previous_room is not None: previous_room.connectRooms(room, room_direction) room.connectRooms(previous_room, reverse_dirs[room_direction]) # Update iteration variables previous_room = room room_count += 1 # THIS STEP DOWNWARD WILL CREATE NORTH-SOUTH CONNECTIONS AT RANDOM POINTS IN THE MAP # set room_count to zero again room_count = 0 # set x and y to zero x = 0 y = 0 # set another variable index to zero # create an array range to hold choices choices = [False, True, False, False, True] # loop while room_count is less than num_rooms while room_count < num_rooms: # if y is less than size_y if y < size_y - 1: # randomize choices # if true set a northward position if random.choice(choices): # connect with the room to the north self.grid[y][x].connectRooms(self.grid[y + 1][x], "n") self.grid[y + 1][x].connectRooms(self.grid[y][x], "s") # increment x x += 1 # increment room_count room_count += 1 # if x is at the last position increment y and reset x if x == size_x: x = 0 y += 1