1

I am remaking the question I made here based on the feedback given to me. If there is still something unclear in my question please let me know.

Explanation for the game: Increasing number game where the users has to guess before the number is going to stop increasing. This is purely a random chance and is done by clicking on a button by the user. Number is calculated on the server side after each game. Number will be increasing by 0.01 starting from 1.00 until the number calculated on the server side this process of number increasing will be visual also for the users.

Solution I have come up with: Running a background process using apischeduler. Executing the number increasing function every 0.1 seconds which adds 0.01 to the current state of number and sends the state result to frontend using Django Channels. I am pulling and updating the state using database queries. When the end result (number) is reached, new number will be calculated and there will be a timer running before new game begins.

That all this seems odd considering I am calling a function in the background every 0.1 seconds forever. I can not figure out how to complete the task differently though. Is there a better solution/more efficient way of doing what I am trying to achieve?

Code example for the increasing part and sending it to the front end:

jobs.py

# Running this function every 0.1 seconds.
def increaseNumber():
    gameObj = Game.objects.latest('round_start_time')
    lastGameObj = Game.objects.filter(round_number=gameObj.round_number-1)[0]

    group_name = 'numbers'
    channel_layer = channels.layers.get_channel_layer()

    if lastGameObj.timer > 0:
        # run timer
        oldTimer = lastGameObj.timer
        newTimer = oldTimer - Decimal(0.1)

        Game.objects.filter(round_number=gameObj.round_number-1).update(timer=newTimer)

        async_to_sync(channel_layer.group_send)(
            group_name,
            {
                'type': 'timer',
                'timer': json.dumps(newTimer, cls = DecimalEncoder)
            }
        )

    else:
        if gameObj.over == False:
            # run game
            getcontext().prec = 3
            oldState = gameObj.result_state
            newState = oldState + Decimal(0.01)
            

            Game.objects.filter(id=gameObj.id).update(result_state=newState)

            if newState >= gameObj.result:
                Game.objects.filter(id=gameObj.id).update(over=True)
                async_to_sync(channel_layer.group_send)(
                    group_name,
                    {
                        'type': 'number_game',
                        'state': json.dumps(newState, cls = DecimalEncoder)
                    }
                )
                return

            async_to_sync(channel_layer.group_send)(
                group_name,
                {
                    'type': 'number_game',
                    'state': json.dumps(newState, cls = DecimalEncoder)
                }
            )

consumer.py

async def number_game(self, event):
    state = event['state']

    await self.send(text_data=json.dumps({
        'state': state
    }))

async def timer(self, event):
    timer = event['timer']

    await self.send(text_data=json.dumps({
        'timer': timer
    }))
Erik
  • 103
  • 9
  • You essentially increase a number serverside for some reasons I do not quite fathom. You get reuquests in, you got a time a number is generated and a second time where you wan a new number - simply track the request timestamps serverside, remember when you last created a new number and if enough time has passed generate a new one - no need for any timed function to be calld 100s per second. – Patrick Artner May 15 '22 at 11:44
  • If you react on user request a fixed amount of requests may be a better metric anyhow for when to change your number – Patrick Artner May 15 '22 at 11:46
  • Its also not very clear where your problem is - give me a better method to do X for working code may not be a good thing to ask on SO. There is no specific answer to that only a multitude of ways to do it – Patrick Artner May 15 '22 at 11:47
  • @PatrickArtner Thank you for the response. I am quite new to this so I can't really understand what you mean with your answer but I try to answer as I understand. The problem with calling a new number generator every let's say 30 seconds is that the game time depends on the size of the random number generated. The reason why I am increasing the number server side is so the user could not cheat on the front end side by feeding the function bigger number than the current state should be. This is also meant as a multiplayer game so everyone would play the same game. – Erik May 15 '22 at 11:54

0 Answers0