当前位置: 首页>>代码示例>>Python>>正文


Python models.Game类代码示例

本文整理汇总了Python中HVZ.main.models.Game的典型用法代码示例。如果您正苦于以下问题:Python Game类的具体用法?Python Game怎么用?Python Game使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Game类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: handle

    def handle(self, *args, **options):
        now = settings.NOW()
        start_date = now.date()

        # The game starts or started on a Tuesday of this week
        if start_date.weekday() in (SUNDAY, MONDAY, TUESDAY):
            start_date -= datetime.timedelta((TUESDAY - start_date.weekday()) % 7)
        else:
            start_date += datetime.timedelta((start_date.weekday() - TUESDAY) % 7)

        end_date = start_date + datetime.timedelta(SATURDAY - TUESDAY)

        if Game.objects.filter(start_date=start_date, end_date=end_date).exists():
            self.stderr.write("You don't need to create a game!")
            return

        game = Game(start_date=start_date, end_date=end_date)
        game.full_clean()
        game.save()

        self.stderr.write(
            "Game created from {:%A %d} to {:%A %d}, {:%B %Y}".format(
                start_date,
                end_date,
                start_date,
            )
        )
开发者ID:Mongoose1021,项目名称:claremontHvZ,代码行数:27,代码来源:newgame.py

示例2: handle

    def handle(self, *args, **options):

        try:
            self.game = Game.imminent_game()
        except Game.DoesNotExist:
            self.stderr.write("No currently-running game found.")
            call_command('newgame', stdout=self.stdout, stderr=self.stderr)
            self.game = Game.imminent_game()

        self.schools = list(School.objects.all())
        self.dorms = list(Building.dorms().all())

        if len(self.schools) == 0 or len(self.dorms) == 0:
            call_command(
                'loaddata',
                os.path.join('HVZ', 'main', 'fixtures', 'production.json'),
                stdout=self.stdout,
                stderr=self.stderr,
            )
            self.schools = list(School.objects.all())
            self.dorms = list(Building.dorms().all())

        num_players = options.get('players') or NUM_PLAYERS
        num_ozs = options.get('ozs') or NUM_OZS

        self.password = options.get('password') or PASSWORD

        self.year = settings.NOW().year

        players = self.make_players(num_players)
        Player.objects.bulk_create(players)

        self.pick_ozs(num_ozs)
开发者ID:Mongoose1021,项目名称:claremontHvZ,代码行数:33,代码来源:randomplayers.py

示例3: make_meals

    def make_meals(self, num_meals):
        humans = list(Player.current_players().filter(team='H'))
        zombies = list(Player.current_players().filter(team='Z'))
        
        g = Game.imminent_game()

        days = (g.end_date - g.start_date).days

        day = g.start_date
        while day < g.end_date:

            meals_per_hour = [0 for i in xrange(24)]
            for i in xrange(int(num_meals / days)):
                meals_per_hour[int(random.gauss(13, 4)) % 24] += 1

            for hour in xrange(24):

                for meal in xrange(meals_per_hour[hour]):
                    z = int(random.random() * len(zombies))
                    h = int(random.random() * len(humans))

                    Meal(
                        eater=zombies[z],
                        eaten=humans[h],
                        time=datetime.combine(day, time(hour=hour)),
                        location=random.choice(Building.objects.all()),
                    ).save()

                    # Instead of retrieving the entire zombie and human lists
                    # again, why don't we just add the human to the zombie
                    # horde ourselves?
                    zombies.append(humans.pop(h))

            day += timedelta(days=1)
开发者ID:Mongoose1021,项目名称:claremontHvZ,代码行数:34,代码来源:randomhistory.py

示例4: get_offset

def get_offset():
    """Return the number of days since game start."""
    try:
        g = Game.imminent_game()
    except Game.DoesNotExist:
        return 0
    return (settings.NOW().date() - g.start_date).days
开发者ID:JoshPetrack,项目名称:claremontHvZ,代码行数:7,代码来源:forms.py

示例5: clean

    def clean(self, *args, **kwargs):
        cleaned_data = super(MealForm, self).clean(*args, **kwargs)

        g = Game.imminent_game()

        # Check that day and time exist
        if not 'day' in cleaned_data:
            raise forms.ValidationError("Somehow you didn't specify the day.")

        if not 'time' in cleaned_data:
            raise forms.ValidationError("Somehow you didn't select a time.")

        feed_date = g.start_date + datetime.timedelta(days=int(cleaned_data['day']))

        if feed_date < g.start_date:
            raise forms.ValidationError("Can't have eaten before the game!")

        if feed_date > g.end_date:
            raise forms.ValidationError("Can't have eaten after the game ended!")

        feed_time = datetime.datetime.combine(feed_date, cleaned_data['time'])

        if feed_time > settings.NOW():
            raise forms.ValidationError("You can't eat in the future, bro.")

        cleaned_data['time'] = feed_time
        return cleaned_data
开发者ID:JoshPetrack,项目名称:claremontHvZ,代码行数:27,代码来源:forms.py

示例6: save

    def save(self, commit=False):
        def grab(s):
            return self.cleaned_data[s]

        game = Game.nearest_game()
        player = Player.user_to_player(self.user, game)

        self.thread = Thread(
            game=game,
            team=grab('team'),
            title=grab('title'),
            slug=slugify(grab('title')),
        )

        self.thread.save()

        post = Post(
            author=player,
            thread=self.thread,
            body=grab('post_body'),
            created=settings.NOW(),
        )

        if commit:
            post.save()

        return self.thread
开发者ID:Mongoose1021,项目名称:claremontHvZ,代码行数:27,代码来源:forms.py

示例7: save

    def save(self, commit=True):
        """Save the player, creating or updating the user if necessary."""
        player = super(RegisterForm, self).save(commit=False)

        def grab(s):
            return self.cleaned_data.get(s)

        email = grab('email')
        password = grab('password1')

        try:
            user = User.objects.get(email=email)
            user.set_password(password)

        except User.DoesNotExist:
            user = User.objects.create_user(
                email=email,
                username=email,
                password=password,
            )

        finally:
            user.first_name = grab("first_name")
            user.last_name = grab("last_name")
            user.full_clean()
            user.save()

        player.user = user
        player.game = Game.imminent_game()

        if commit == True:
            player.save()

        return player
开发者ID:haaksmash,项目名称:claremontHvZ,代码行数:34,代码来源:forms.py

示例8: game

    def game(self):
        if self._game:
            return self._game
        try:
            self._game = Game.nearest_game()
        except Game.DoesNotExist:
            raise PermissionDenied("You need to create a game!")

        return self._game
开发者ID:Mongoose1021,项目名称:claremontHvZ,代码行数:9,代码来源:mixins.py

示例9: get_context_data

    def get_context_data(self, **kwargs):
        context = super(PlayerListView, self).get_context_data(**kwargs)
        context['game_season'] = Game.nearest_game().season()

        context['schools'] = School.objects.all().annotate(
            num_players=Count('player_set')
        ).order_by('-num_players')

        context['years'] = map(str, sorted(set([p.grad_year for p in Player.current_players()])))
        context['school'] = self.kwargs.get('school', '')
        context['gradyear'] = self.kwargs.get('gradyear', '')

        return context
开发者ID:Mongoose1021,项目名称:claremontHvZ,代码行数:13,代码来源:views.py

示例10: handle

    def handle(self, *args, **options):
        try:
            self.game = Game.imminent_game()
        except Game.DoesNotExist:
            # Create game and players
            call_command(
                'randomplayers',
                players=options.get('players'),
                ozs=options.get('ozs'),
                password=options.get('password'),
                stdout=self.stdout,
                stderr=self.stderr,
            )
            self.game = Game.imminent_game()

        humans = Player.current_players().filter(team='H')
        zombies = Player.current_players().filter(team='Z')
        if not len(humans) or not len(zombies):
            self.stderr.write(
                '\n'.join(["There are no players in the current game.",
                           "To generate a batch of random players, run",
                           "    ./manage.py randomplayers"]))
            return

        num_meals = options.get('meals') or len(humans) / 2

        self.stdout.write("Creating {} meals".format(num_meals))

        if not num_meals:
            return

        if len(humans) < num_meals:
            self.stderr.write(
                "There are only {} humans in the current game.".format(len(humans))
            )
            num_meals = len(humans)

        meals = self.make_meals(num_meals)
        Meal.objects.bulk_create(meals)
开发者ID:Mongoose1021,项目名称:claremontHvZ,代码行数:39,代码来源:randomhistory.py

示例11: weekday_choices

def weekday_choices():
    """Returns a list of offsets from the start of the current game."""
    try:
        g = Game.imminent_game()
    except Game.DoesNotExist:
        return xrange(7)

    # Bounds on when the meal can have occurred
    start = g.start_date
    end = min(settings.NOW().date(), g.end_date)

    return (
        (i, CAL.formatweekday((start+datetime.timedelta(days=i)).weekday(), 3))
        for i in range((end-start).days+1)
    )
开发者ID:JoshPetrack,项目名称:claremontHvZ,代码行数:15,代码来源:forms.py

示例12: test_invalid_time

    def test_invalid_time(self):
        """Ensure that eating times only occur within the game's timeline."""
        g = Game.imminent_game()

        num_z = Player.objects.filter(team="Z").count()
        self.assertEqual(Meal.objects.count(), 0)

        m = MEAL.copy()
        m["day"] = -1

        c = Client()
        c.post(reverse("login"), ROB_ZOMBIE)
        c.post(reverse("feed_eat"), m)

        # Ensure that no meal was created, and no new zombies have spawned.
        self.assertEqual(Meal.objects.count(), 0)
        self.assertEqual(Player.objects.filter(team="Z").count(), num_z)
开发者ID:haaksmash,项目名称:claremontHvZ,代码行数:17,代码来源:tests.py

示例13: inject_outbreak_percentage

def inject_outbreak_percentage(request):
    try:
        latest_game = Game.games(started=True).latest()
    except Game.DoesNotExist:
        # Just return an arbitrary sane value
        return {'outbreak_percent': 96}

    players = Player.objects.filter(game=latest_game)
    humans = players.filter(team='H')

    nPlayers = players.count()

    if nPlayers > 0:
        percent = humans.count() * 100. / nPlayers
    else:
        percent = 100

    return {'outbreak_percent': min(96, percent)}
开发者ID:JoshPetrack,项目名称:claremontHvZ,代码行数:18,代码来源:context_processors.py

示例14: handle

    def handle(self, *args, **options):

        try:
            self.game = Game.imminent_game()
        except Game.DoesNotExist:
            self.stderr.write("No currently-running game found.")
            return

        num_players = options.get('players')
        num_ozs = options.get('ozs') or NUM_OZS

        self.password = options.get('password') or PASSWORD

        self.year = settings.NOW().year

        players = self.make_players(num_players)
        Player.objects.bulk_create(players)

        self.pick_ozs(num_ozs)
开发者ID:haaksmash,项目名称:claremontHvZ,代码行数:19,代码来源:randomplayers.py

示例15: get_context_data

    def get_context_data(self, *args, **kwargs):
        context = super(LandingPage, self).get_context_data(*args, **kwargs)

        if not self.request.user.is_authenticated():
            form = PrettyAuthForm()
        else:
            form = None

        context['login_form'] = form
        context['is_landing_page'] = True
        try:
            context['latest_meals'] = (
                Meal.objects.filter(
                    eater__game=Game.games(started=True).latest(),
                ).order_by('-time')[:20])
        except Game.DoesNotExist:
            context['latest_meals'] = []

        return context
开发者ID:jhb563,项目名称:claremontHvZ,代码行数:19,代码来源:views.py


注:本文中的HVZ.main.models.Game类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。