Logo Search packages:      
Sourcecode: gameclock version File versions  Download package


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# gameclock - a simple chess/game clock
# Copyright (C) 2008 Antoine Beaupré <anarcat@koumbit.org>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import time
import math
import getopt
import sys

version = "2.1"
verbose = 0 # 0 means not verbose, higher numbers show more information, see maybe_print for more info

00028 class Clock:
    """The main clock engine

    Each clock is an instance of this class. This could be considered
    like a merge between a controler and a model in an MVC
    model. However, this software isn't based on the MVC model in any
    remote way.
    This should be pretty precise and doesn't lag from empirical
    observations (watching the clocks compared to the Gnome clock
    last_start = 0 # 0 if stopped
    text = "" # rendered version of the clock
    dead = False
    game = None
    # a clock is part of a chained list
    next = None
    # usually, clocks go backwards, but some games might require it to go other ways
    factor = -1

00049     def __init__(self, game):
        """Setup the clock engine
        The clock is stopped by default and the display is refreshed
        self.time = game.default_time
        self.dead = self.time < 0 # calculated only after update() and should be used only this way, it is a cache
        self.game = game

00059     def start(self):
        """Start the timer
        This marks the new timestamp and sets the background color
        self.last_start = time.time()
        # no need to update, time shouldn't have changed since last stop

00067     def stop(self):
        """Stop the timer
        This computes the new cumulatative time based on the start
        timestamp. It resets the timestamp to zero to mark the timer as
        This also resets the event box's color and triggers an update of
        the label.
        XXX: Note that this function takes *some* time to process. This
        time is lost and not given to any participant. Maybe that should
        be fixed for the clock to be really precised, by compensation
        for the duration of the function.
        Another solution would be to create a thread for the Game engine
        if self.last_start:
            self.time = self.get_time()
            self.last_start = 0

00089     def pause(self):
        """pause/unpause the timer
        this will start the timeer if stopped and stop it if started
        if self.last_start:
            self.time = self.get_time()
            self.last_start = 0          

    def running(self):
        return self.last_start

00104     def get_time(self):
        """return the current time of the clock in ms"""
        if self.last_start:
            diff = time.time() - self.last_start
            diff = 0
        return self.time + (self.factor * diff*1000)

00112     def update(self):
        """Refresh the display of the clock's widget"""
        # convert to seconds because that's what gmtime wants
        miliseconds = self.get_time()
        secs = miliseconds/1000
        self.text = time.strftime("%H:%M:%S", time.gmtime(abs(secs)))
        days = abs(secs) / ( 24 * 60 * 60 )
        if days >= 1:
            self.text = "%dd " % days + self.text
        self.dead = secs < 0
        if self.dead:
            self.text = "-" + self.text
        if self.game.miliseconds:
            mantissa = abs(miliseconds) - (math.floor(abs(secs))*1000)
            self.text += ".%03d" % (mantissa)
        return self.text

00129     def __str__(self):
        """make a better string representation of the objects
        we basically dump all variables and some functions
        return "  clock engine %s time: %d last: %d diff: %f dead: %d text: %s\n  next %s" % ( object.__str__(self), self.time, self.last_start, time.time() - self.last_start, self.dead, self.text, self.next)

00136 class Game:
    """the game engine
    this regroups two clocks and handles turn switches

    to simplify the code logic, this is basically the "Blitz" mode

    # the number of turns played
    turns = 0
    miliseconds = False
    mode = 'blitz'
    default_time = 2 * 60 * 1000 # in ms
    default_fisher = 10 # in seconds, default is used only by the UI
    default_players = 2 # default number of players
    default_game = "BlitzGame" # the default game type. note that this cannot be FisherGame because of the way the UI is setup.

    # the clocks in the game
    # in chess there are two clocks, but there can be more. this is simply a list
    cur_clock = None
    first_clock = None

    def __init__(self, clocks, miliseconds):
        self.miliseconds = miliseconds

        # the clock engines
        self.cur_clock = self.first_clock = p = Clock(self)
        for i in range(clocks-1):
            p.next = Clock(self)
            p = p.next

00169     def start(self):
        """start the game
        this basically starts the clock

00177     def end_turn(self):
        """end the turn
        this is the handler for the main button. it will stop the
        active clock and start the other and switch the active clock
        # XXX: we might lose a few ms here
        self.cur_clock = self.next_clock()
        self.turns += 1

    def next_clock(self):
        return self.cur_clock.next or self.first_clock

00192     def pause(self):
        """pause the game
        this just pauses the current clock

00199     def switch_clock(self):
        """change the current clock"""
        self.cur_clock = self.next_clock()

00203     def get_turns(self):
        """the number of complete turns played
        a 'complete turn' is a turn played by each player

        this is 1-based, i.e. when the game starts, it's turn 1, after
        every player has played once, it's turn 2, etc.
        return math.floor(self.turns/self.count_players()) + 1

    def count_players(self):
        p = self.first_clock
        count = 0
        while p:
            count += 1
            p = p.next
        return count

    def dead(self):
        p = self.first_clock
        while p:
            if p.dead:
                return True
            p = p.next
        return False

    def running(self):
        return self.cur_clock.running()

00232     def __str__(self):
        """make a better string representation of the objects
        we basically dump all variables and some functions
        return "  game engine %s\n  turns: %f / %d miliseconds: %d\n  first %s\n  current %s" % ( object.__str__(self), self.turns, self.get_turns(), self.miliseconds, self.first_clock, self.cur_clock)

00239 class BlitzGame(Game):
    """a regular, blitz-style chess game. note that this is just an alias to the base Game class which implements everything"""

00243 class FisherGame(Game):
    """a regular, blitz-style chess game"""
    fisher = 0

    def __init__(self, clocks, miliseconds, fisher):
        self.fisher = fisher
        Game.__init__(self, clocks, miliseconds)
00251     def end_turn(self):
        """end the turn, fisher style

        this increments the current clock before switching turns as normal
        self.cur_clock.time += self.fisher

00259 class ClassicGame(Game):
    """a classic board-type game

    every player gets N time to play his turn and his clock is reset at the end of his turn

00265     def end_turn(self):
        """override the end_turn function to reset the timers at the end of turns"""
        tmp = self.cur_clock
        tmp.time = self.default_time

00272 class HourglassGame(Game):
    """hourglass modelisation

    this is like an hourglass on a table that is flipped at the end of each turn

    note that this will probably work very well with > 2 players.

00280     def __init__(self, clocks, miliseconds):
        """this overrides the base constructor to make only one clock have an initial time

        basically, this is to represent that when you start it, the hour glass is empty on one side
        Game.__init__(self, clocks, miliseconds)
        p = self.first_clock.next
        while p:
            p.time = 0
            p = p.next

00291     def start(self):
        """reimplement the start() function altogether

        make sure all the clocks are started and they are in the right direction
        p = self.first_clock
        while p:
            # reverse the other clocks
            if p == self.cur_clock:
                p.factor = -1
                p.factor = 1
            p = p.next

00307     def end_turn(self):
        """reimplement the end_turn function altogether

        we go to the next clock, stop it, reverse its direction and
        start it again
        self.cur_clock = self.next_clock()
        p = self.first_clock
        while p:
            if p == self.cur_clock:
                p.factor = -1
                p.factor = 1
            p = p.next
        self.turns += 1

def usage():
    """gameclock v%s  Copyright (C) 2008  Antoine Beaupré
This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it
under certain conditions.
For details see the COPYRIGHT file distributed along this program.

  %s [ -h | -v ... | -f ]

  -h --help: display this help
  -v --verbose: display progress information to stdout. repeating the flag will show more information
  -f --fullscreen: start in fullscreen mode

See the manpage for more information."""
    print usage.__doc__ % (version, sys.argv[0])

if __name__ == "__main__":
        opts, args = getopt.getopt(sys.argv[1:], "hvf:p:", ["help", "verbose", "fullscreen"])
    except getopt.GetoptError, err:
        # print help information and exit:
        print "\nError: " + str(err) # will print something like "option -a not recognized"

    from gtkui import GameclockUI
    clock = GameclockUI()
    for o, a in opts:
        if o in ("-v", "--verbose"):
            clock.verbose += 1
        elif o in ("-h", "--help"):
        elif o in ("-f", "--fullscreen"):
            clock.fullscreen = True
            assert False, "unhandled option"
    clock.maybe_print('running with verbosity: %d' % clock.verbose)

Generated by  Doxygen 1.6.0   Back to index