view frontends/wix/card_game.py @ 86:4b5f2d55b6ac

wix: Tarot panel now appear on top of groupchat window when a Tarot game is started
author Goffi <goffi@goffi.org>
date Tue, 11 May 2010 13:06:05 +0930
parents 1ac759ea28c3
children 66d784082930
line wrap: on
line source

#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
wix: a SAT frontend
Copyright (C) 2009, 2010  Jérôme Poisson (goffi@goffi.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
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU 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 wx
import os.path, glob
import random
import pdb
from logging import debug, info, error
from tools.jid  import JID
from quick_frontend.quick_chat import QuickChat
from contact_list import ContactList

CARD_WIDTH = 74
CARD_HEIGHT = 136
MIN_WIDTH = 950 #Minimum size of the panel
MIN_HEIGHT = 500

class Card():
    """This class is used to represent a card, graphically and logically"""

    def __init__(self, file):
        """@param file: path of the PNG file"""
        self.bitmap = wx.Image(file).ConvertToBitmap()
        root_name = os.path.splitext(os.path.basename(file))[0]
        self.family,self.value=root_name.split('_')
        self.bout = True if self.family=="atout" and self.value in ["1","21","excuse"] else False

        print "Carte:",self.family, self.value, self.bout


    def draw(self, dc, x, y):
        """Draw the card on the device context
        @param dc: device context
        @param x: abscissa 
        @param y: ordinate"""
        dc.DrawBitmap(self.bitmap, x, y, True)


class CardPanel(wx.Panel):
    """This class is used to display the cards"""

    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        self.SetMinSize(wx.Size(MIN_WIDTH, MIN_HEIGHT))
        self.load_cards("/home/goffi/dev/divers/images/cards/")
        self.selected = None #contain the card to highlight
        self.hand_size = 13 #number of cards in a hand
        self.visible_size = CARD_WIDTH/2 #number of pixels visible for cards
        self.hand = random.sample(self.deck, self.hand_size)
        self.SetBackgroundColour(wx.GREEN)
        self.Bind(wx.EVT_SIZE, self.onResize)
        self.Bind(wx.EVT_PAINT, self.onPaint)
        self.Bind(wx.EVT_MOTION, self.onMouseMove)
        self.Bind(wx.EVT_LEFT_UP, self.onMouseClick)

    def load_cards(self, dir):
        """Load all the cards in memory
        @param dir: directory where the PNG files are"""
        self.cards={}
        self.deck=[]
        self.cards["atout"]={} #As Tarot is a french game, it's more handy & logical to keep french names
        self.cards["pique"]={} #spade
        self.cards["coeur"]={} #heart
        self.cards["carreau"]={} #diamond
        self.cards["trefle"]={} #club
        for file in glob.glob(dir+'/*_*.png'):
            card = Card(file)
            self.cards[card.family, card.value]=card
            self.deck.append(card)
        """for value in map(str,range(1,22))+['excuse']:
            self.idx_cards.append(self.cards["atout",value])
        for family in ["pique", "coeur", "carreau", "trefle"]:
            for value in map(str,range(1,11))+["valet","cavalier","dame","roi"]:
                self.idx_cards.append(self.cards[family, value])"""  #XXX: no need to sort the cards !

    def _is_on_hand(self, pos_x, pos_y):
        """Return True if the coordinate are on the hand cards"""
        if pos_x > self.orig_x and pos_y > self.orig_y \
           and pos_x < self.orig_x + (len(self.hand)+1) * self.visible_size \
           and pos_y < self.end_y:
           return True
        return False

    def onResize(self, event):
        self._recalc_ori()

    def _recalc_ori(self):
        """Recalculate origines, must be call when size change"""
        self.orig_x = (self.GetSizeTuple()[0]-(len(self.hand)+1)*self.visible_size)/2 #where we start to draw cards
        self.orig_y = self.GetSizeTuple()[1] - CARD_HEIGHT - 20
        self.end_y = self.orig_y + CARD_HEIGHT

    def onPaint(self, event):
        dc = wx.PaintDC(self)
        x=self.orig_x
        for card in self.hand:
            card.draw(dc,x,self.orig_y - 30 if card == self.selected else self.orig_y)
            x+=self.visible_size

    def onMouseMove(self, event):
        pos_x,pos_y = event.GetPosition()
        if self._is_on_hand(pos_x, pos_y):
           try:
               self.selected = self.hand[(pos_x-self.orig_x)/self.visible_size]
           except IndexError:
               self.selected = self.hand[-1]
           self.Refresh()
        else:
            self.selected = None
            self.Refresh()

    def onMouseClick(self, event):
        print "mouse click:",event.GetPosition()
        pos_x,pos_y = event.GetPosition()
        if self._is_on_hand(pos_x, pos_y):
           idx = (pos_x-self.orig_x)/self.visible_size
           if idx == len(self.hand):
               idx-=1
           if self.hand[idx] == self.selected:
               del self.hand[idx]
               self._recalc_ori()
               self.Refresh()

class CardGame(wx.Frame, QuickChat):
    """The window used to play all kind of card games"""

    def __init__(self, host):
        wx.Frame.__init__(self, None, pos=(0,0), size=(950,500))

        self.host = host
        
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.panel = CardPanel(self)
        self.sizer.Add(self.panel, 1, flag=wx.EXPAND)
        self.SetSizer(self.sizer)
        self.SetAutoLayout(True)
       

        #events