[Answer]-Django turn based browser game – database design to handle separate time steps

1πŸ‘

βœ…

I think you have it mostly figured out. Two databases, default and future.

DATABASES = {
    'default': {
        'NAME': 'default',
        'ENGINE': 'django.db.backends.mysql',
        'USER': '',
        'PASSWORD': '',
    },
    'future': {
        'NAME': 'future',
        'ENGINE': 'django.db.backends.mysql',
        'USER': '',
        'PASSWORD': '',
    },
}

Write your views/whatever normally using models as usual. These will be written to the defaultdatabase as you are probably used to.


Create a management command which updates the game state… (You could also throw this code into a Celery task or something else, but for this answer I plan to invoke via command-line using cron scheduler.)

# project/app/management/commands/run_turn.py

from django.conf import settings
from django.core.management.base import BaseCommand
import subprocess
from optparse import make_option

def copy_default_to_future():
    # Copy database before acting on game state
    # use the subprocess library for bash execution of mysql/postgres commands

    # ...

def copy_future_to_default():
    # Copy database after acting on game state
    # use the subprocess library for bash execution of mysql/postgres commands

    # ...

def upload_backup_to_cloud():
    # i recommend using django-cumulus and a custom backups storage container

    # ...

class Command(BaseCommand):
    args = '<attachment_path attachment_path ...>'
    help = 'Processes game state at end of turn'

    option_list = BaseCommand.option_list + (
        make_option('-u', '--upload-backup',
            action='store_true',
            dest='upload',
            default=False,
            help='Upload database export to cloud object storage'),
        )

    def handle(self, *args, **options):
         if options.get('upload', None):
             upload_backup_to_cloud()

         copy_default_to_future()

         # ... change your gamestate
         for player in Player.objects.using('future').all():
             player.increment()
         # ...

         copy_future_to_default()

         print "Game state updated."

patrick@lucca:~$ crontab -e

@hourly /home/patrick/.virtualenvs/browsergame/bin/python /path/to/project/manage.py run_turn --upload-backup

References:

πŸ‘€pztrick

Leave a comment