45 lines
1.6 KiB
Python
45 lines
1.6 KiB
Python
import random
|
|
import string
|
|
|
|
from django.db import models
|
|
from django.utils import timezone
|
|
|
|
|
|
def generate_code(length):
|
|
return "".join([random.choice(string.ascii_lowercase)
|
|
for i in range(length)])
|
|
|
|
|
|
class Game(models.Model):
|
|
ACCESS_CODE_LENGTH = 6
|
|
access_code = models.CharField(db_index=True, unique=True,
|
|
max_length=ACCESS_CODE_LENGTH)
|
|
game_turn = models.IntegerField(default=0)
|
|
GAME_PHASE_LOBBY = 0
|
|
GAME_PHASE_ACTIVE = 1
|
|
GAME_PHASE_PARLEY = 2
|
|
GAME_PHASE_END = 3
|
|
game_phase = models.IntegerField(default=GAME_PHASE_LOBBY)
|
|
created = models.DateTimeField()
|
|
ended = models.DateTimeField(null=True, default=None)
|
|
|
|
# from http://stackoverflow.com/a/11821832
|
|
def save(self, *args, **kwargs):
|
|
# object is being created, thus no primary key field yet
|
|
if not self.pk:
|
|
# Make sure access_code is unique before using it.
|
|
access_code = generate_code(Game.ACCESS_CODE_LENGTH)
|
|
while Game.objects.filter(access_code=access_code).exists():
|
|
access_code = generate_code(Game.ACCESS_CODE_LENGTH)
|
|
self.access_code = access_code
|
|
self.created = timezone.now()
|
|
if self.ended is None and self.game_phase == Game.GAME_PHASE_END:
|
|
self.ended = timezone.now()
|
|
super(Game, self).save(*args, **kwargs)
|
|
|
|
|
|
class Player(models.Model):
|
|
game = models.ForeignKey(Game, on_delete=models.CASCADE, db_index=True)
|
|
name = models.CharField(max_length=80)
|
|
unique_together = (("game", "name"),)
|