Advertisement
Guest User

Untitled

a guest
Jul 5th, 2011
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 17.71 KB | None | 0 0
  1. # ver 4.1
  2. # date 13.4.2011
  3. # -*- coding:Utf-8 -*-
  4. import os,sys
  5. import pygame
  6. #from pygame.locals import *
  7. import time
  8. #MOUSEBUTTONDOWN
  9.  
  10. WHITECOLOR = (190,190,210)
  11. BLACKCOLOR = (100,100,100)
  12. class ResManager(object):
  13.     u"""Set data path and load image """
  14.     #x =  os.getcwd()
  15.     def __init__(self, data_dir = '',
  16.                  image_dir = 'img'):
  17.         self.data_dir = data_dir
  18.         self.image_dir = image_dir
  19.  
  20.  
  21.  
  22.     def get_image(self, name):
  23.         fullname = os.path.join(self.data_dir, os.path.join(self.image_dir, name))
  24.  
  25.         try:
  26.             image = pygame.image.load(fullname)
  27.         except pygame.error, message:
  28.             return None
  29.         else:
  30.             image = image.convert_alpha()
  31.             return image
  32.            
  33. manager = ResManager( data_dir = '\\'.join((sys.argv[0].split('\\')[0:-1]))+'\\') #os.getcwd())
  34.          
  35.            
  36. class Figure(object):
  37.     u"""parent calss """
  38.    
  39.     def __init__(self,pos =None,image=None,color = None):
  40.         self.color = color
  41.        
  42.         image = manager.get_image(image)
  43.         # если файл фигуры ненайден
  44.         if not image and self.name:
  45.             #self.font = pygame.font.Font(None, 24)
  46.             self.font = pygame.font.SysFont('arial', 20)
  47.             # в качестве картинки используем текст с именем фигуры
  48.             image = self.font.render(' '+self.name, 0, {'black':(0,0,0),'white':(250,250,250)}[self.color])
  49.         self.image = image
  50.         self.pos = pos
  51.          
  52.     def posget(self):
  53.         return self._posicion
  54.      
  55.     def moveAndDraw(self,val):
  56.         'clear kvadrat'
  57.         if hasattr(self,'_posicion'):
  58.             x,y = self._posicion
  59.             d = 60
  60.             if x%2 != y%2: col = BLACKCOLOR
  61.             else: col = WHITECOLOR
  62.        
  63.             x1,y1 = x*d,y*d
  64.             pygame.draw.polygon(display,col, ((x1,y1), (x1,y1+d), (x1+d,y1+d), (x1+d,y1) ))
  65.        
  66.         'рисуем фигурку'
  67.         self._posicion = val
  68.         self.redraw()
  69.    
  70.     pos = property(posget, moveAndDraw)
  71.    
  72.     def redraw(self):
  73.         x,y = self._posicion
  74.         display.blit(self.image, (x*60,y*60))
  75.     def clear(self):
  76.         # закрасим после себя квадратик
  77.         x,y = self._posicion
  78.         d = 60
  79.         if x%2 != y%2: col = BLACKCOLOR
  80.         else: col = WHITECOLOR
  81.        
  82.         x1,y1 = x*d,y*d
  83.         pygame.draw.polygon(display,col, ((x1,y1), (x1,y1+d), (x1+d,y1+d), (x1+d,y1) ))
  84.        
  85.     def snapshoot(self):
  86.         return {self._posicion:self.color}
  87.     def getPossibleMove(self,*k,**kw):
  88.         raise Exception,'getPossibleMove method must be overridden in child'
  89.      
  90. class WhitePeshka(Figure):
  91.     name = u'пешка'
  92.     def getPossibleMove(self,snap):
  93.         posmov = []
  94.         figx,figy = self._posicion
  95.         if figy == 6: na4hod =3 # в начале пешка може ходить через клетку
  96.         else: na4hod =2
  97.        
  98.         for y in xrange(1,na4hod):
  99.             p = (figx, figy - y)
  100.             if p in snap:
  101.                 break
  102.             else:
  103.                 posmov.append(p)
  104.    
  105.         p = (figx+1,figy+1)
  106.         if p in snap and snap[p] != self.color:
  107.              posmov.append(p)
  108.              
  109.         p =(figx-1,figy+1)
  110.         if p in snap and snap[p] != self.color:
  111.              posmov.append(p)
  112.         return posmov
  113.    
  114. class BlackPeshka(Figure):
  115.     name = u'пешка'
  116.     def getPossibleMove(self,snap):
  117.         posmov = []
  118.         figx,figy = self._posicion
  119.         if figy == 1: na4hod =3 # в начале пешка може ходить через клетку
  120.         else: na4hod =2
  121.        
  122.         for y in xrange(1,na4hod):
  123.             p = (figx,y + figy)
  124.             if p in snap:
  125.                 break
  126.             else:
  127.                 posmov.append(p)
  128.    
  129.         p = (figx+1,figy+1)
  130.         if p in snap and snap[p] != self.color:
  131.              posmov.append(p)
  132.              
  133.         p =(figx-1,figy+1)
  134.         if p in snap and snap[p] != self.color:
  135.              posmov.append(p)
  136.         return posmov
  137.    
  138. class Ladia(Figure):
  139.     name = u'ладья'
  140.     def getPossibleMove(self,snap):
  141.         posmov = []
  142.         figx,figy =  self._posicion
  143.        
  144.         def generator():
  145.             for g in      (lambda: (figx,  figy+x),
  146.                            lambda: (figx,  figy-x),
  147.                            lambda: (figx+x,  figy),
  148.                            lambda: (figx-x,  figy)):
  149.                 yield g
  150.  
  151.         for foo in generator():
  152.  
  153.             for x in xrange(1,8):
  154.                 figpos = foo()
  155.                 if figpos in snap:
  156.                     if snap[figpos] != self.color:
  157.                         posmov.append(figpos)
  158.                     break  
  159.                 else:    
  160.                     posmov.append(figpos)
  161.         return posmov
  162.    
  163. class Kon(Figure):
  164.     name = u'конь'
  165.     def getPossibleMove(self,snap):
  166.         posmov = []
  167.         figx,figy = self._posicion
  168.  
  169.         for figpos in ((figx-1,figy+2),
  170.                         (figx-1,figy-2),
  171.                         (figx+1,figy+2),
  172.                         (figx+1,figy-2),
  173.                         (figx-2,figy+1),
  174.                         (figx-2,figy-1),
  175.                         (figx+2,figy+1),
  176.                         (figx+2,figy-1)):
  177.             if figpos in snap:
  178.                 if snap[figpos] != self.color:
  179.                     posmov.append(figpos)
  180.             else:    
  181.                 posmov.append(figpos)
  182.         return posmov
  183.    
  184. class Slon(Figure):
  185.     name = u'слон'
  186.     def getPossibleMove(self,snap):
  187.         posmov = []
  188.         figx,figy = self._posicion
  189.        
  190.         def generator():
  191.             for g in      (lambda: (figx+x,  figy+x),
  192.                            lambda: (figx-x,  figy-x),
  193.                            lambda: (figx+x,  figy-x),
  194.                            lambda: (figx-x,  figy+x)):
  195.                 yield g
  196.  
  197.         for foo in generator():
  198.  
  199.             for x in xrange(1,8):
  200.                 figpos = foo()
  201.                 if figpos in snap:
  202.                     if snap[figpos] != self.color:
  203.                         posmov.append(figpos)
  204.                     break  
  205.                 else:    
  206.                     posmov.append(figpos)
  207.         return posmov
  208.                    
  209. class Ferz(Figure):
  210.     name = u'ферзь'
  211.     def getPossibleMove(self,snap):
  212.         posmov = []
  213.         figx,figy = self._posicion
  214.        
  215.         def generator():
  216.             for g in      (lambda: (figx+x,  figy+x),
  217.                            lambda: (figx-x,  figy-x),
  218.                            lambda: (figx+x,  figy-x),
  219.                            lambda: (figx-x,  figy+x),
  220.                            lambda: (figx,  figy+x),
  221.                            lambda: (figx,  figy-x),
  222.                            lambda: (figx+x,  figy),
  223.                            lambda: (figx-x,  figy)):
  224.                 yield g
  225.  
  226.         for foo in generator():
  227.  
  228.             for x in xrange(1,8):
  229.                 figpos = foo()
  230.                 if figpos in snap:
  231.                     if snap[figpos] != self.color:
  232.                         posmov.append(figpos)
  233.                     break  
  234.                 else:    
  235.                     posmov.append(figpos)
  236.         return posmov
  237.    
  238. class Korol(Figure):
  239.     name = u'король'
  240.     def getPossibleMove(self,snap):
  241.         posmov = []
  242.         figx,figy = self._posicion
  243.        
  244.         for figpos in ( (figx-1,figy+1),
  245.                         (figx-1,figy-1),
  246.                         (figx+1,figy+1),
  247.                         (figx+1,figy-1),
  248.                         (figx,figy+1),
  249.                         (figx,figy-1),
  250.                         (figx+1,figy),
  251.                         (figx-1,figy)):
  252.                        
  253.             if figpos in snap:
  254.                 if snap[figpos] != self.color:
  255.                     posmov.append(figpos)
  256.             else:    
  257.                 posmov.append(figpos)
  258.         return posmov
  259.    
  260. class Singleton(type):
  261.      def __init__(cls, name, bases, dict):
  262.          super(Singleton, cls).__init__(name, bases, dict)
  263.          cls.instance = None
  264.      def __call__(cls,*args,**kw):
  265.          if cls.instance is None:
  266.              cls.instance = super(Singleton, cls).__call__(*args, **kw)
  267.          return cls.instance
  268.        
  269. class Board(list):  
  270.     u"""класс реализует контейнер для фигур"""
  271.     __metaclass__ = Singleton  
  272.  
  273.     # перегрузим + чтоб меньше писать потом
  274.     def __add__(self,val):
  275.         self.append(val)
  276.        
  277.     def drawboard(self,curentfigure= None):
  278.         u""" рисуем клетки """
  279.         display.fill(WHITECOLOR)
  280.         d = 60
  281.         for x in xrange(0,8):
  282.             for y in xrange(0,8):
  283.                 if x%2 != y%2:
  284.                     x1,y1 = x*d,y*d
  285.                     pygame.draw.polygon(display, BLACKCOLOR, ((x1,y1), (x1,y1+d), (x1+d,y1+d), (x1+d,y1) ))
  286.  
  287.         if curentfigure:
  288.             self._drawcurentfigure(display,curentfigure,linecolor = (10,200,10))
  289.  
  290.                    
  291.     def getpos(self,mousexy):
  292.         return mousexy[0]/60,mousexy[1]/60
  293.  
  294.     def getFigure(self,pos) :
  295.         x,y = pos
  296.         if 0>x or x>7 or 0>y or y>7:return None
  297.         for fig in self:
  298.             if fig and fig.pos == pos: return fig
  299.     def killFigure(self,pos):
  300.         for x in xrange(len(self)):
  301.             fig = self[x]
  302.             if fig and fig.pos == pos:
  303.                 fig.clear()
  304.                 del self[x]
  305.                 return
  306.        
  307.  
  308.        
  309.     def initFigure(self):
  310.         for x in xrange(8):
  311.             self + BlackPeshka(pos = (x,1),color = 'black',image='bp.png' )
  312.             self + WhitePeshka(pos = (x,6),color = 'white',image='wp.png')
  313.         self + Ladia(pos = (0,7), color = 'white',image= 'wl.png')
  314.         self + Ladia(pos = (7,7), color = 'white',image= 'wl.png')
  315.         self + Kon(pos = (1,7), color = 'white',image= 'wkon.png')
  316.         self + Kon(pos = (6,7), color = 'white',image= 'wkon.png')
  317.         self + Slon(pos = (2,7), color = 'white',image= 'ws.png')
  318.         self + Slon(pos = (5,7), color = 'white',image= 'ws.png')
  319.         self + Ferz(pos = (3,7), color = 'white',image= 'wf.png')
  320.         self.whiteKorol = Korol(pos = (4,7), color = 'white',image= 'wk.png')
  321.         self + self.whiteKorol
  322.                            
  323.         self + Ladia(pos = (0,0), color = 'black',image= 'bl.png')
  324.         self + Ladia(pos = (7,0), color = 'black',image= 'bl.png')
  325.         self + Kon(pos = (1,0),color = 'black',image= 'bkon.png')
  326.         self + Kon(pos = (6,0),color = 'black',image= 'bkon.png')
  327.         self + Slon(pos = (2,0), color = 'black',image= 'bs.png')
  328.         self + Slon(pos = (5,0),color = 'black',image='bs.png')
  329.         self + Ferz(pos = (3,0),color = 'black',image= 'bf.png')
  330.        
  331.         self.blackKorol = Korol(pos = (4,0),color = 'black',image= 'bk.png')
  332.         self + self.blackKorol
  333.      
  334.     def startgame(self):
  335.         u"""restart game, set default pos figure and vars"""
  336.         self.drawboard()
  337.         #self.board.initFigure(self.manager)
  338.         self.initFigure()
  339.         pygame.display.flip()
  340.        
  341.     def redrawAll(self):
  342.         self.drawboard()
  343.         for fig in self:
  344.             fig.redraw()
  345.        
  346.        
  347.        
  348.     def podsvetka(self,pos,posiblemove):
  349.         self.redrawAll()
  350.         linecolor = (30,30,50)
  351.         x,y = pos
  352.         d = 60
  353.         x1,y1 = x*d,y*d
  354.         #pygame.draw.circle(display,(255,10,0), (x1+30,y1+30), 3)
  355.         self._drawcurentfigure(pos,linecolor = (0,10,200))
  356.         for kletka in posiblemove:
  357.             self._drawcurentfigure(kletka,linecolor = (0,210,20))
  358.            
  359.     def _drawcurentfigure(self,curentfigure,linecolor =  None):
  360.         u"""выделяем выбраную фигуру """      
  361.         x,y = curentfigure
  362.         d = 60
  363.         x1,y1 = x*d,y*d
  364.         w = 3 # ширина линии подсветки
  365.         dx = 3 # смещение во внутрь
  366.         pygame.draw.line(display, linecolor,  (x1+dx,y1+dx    ), (x1+d-dx,y1+dx  ),w)
  367.         pygame.draw.line(display, linecolor,  (x1+dx,y1+dx    ), (x1+dx,y1+d-dx  ),w)
  368.         pygame.draw.line(display, linecolor,  (x1+d-dx,y1+d-dx), (x1+d-dx,y1+dx  ),w)
  369.         pygame.draw.line(display, linecolor,  (x1+dx,y1+d-dx  ), (x1+d-dx,y1+d-dx),w)
  370.         pygame.draw.circle(display,linecolor, (x1+30,y1+30), 3)
  371.            
  372.     def boradSnapshoot(self):
  373.         out = {}
  374.         for fig in self:
  375.             out.update(fig.snapshoot())
  376.         return out
  377.        
  378.     def msg(self,text):
  379.         for x in range(0,55):
  380.             font = pygame.font.SysFont('arial', 50+x/2)
  381.             image = font.render(text, 100, (4*x,4*x,1*x))
  382.             display.blit(image, (90-x,210))
  383.             pygame.display.flip()
  384.             time.sleep(0.011)
  385.        
  386.        
  387.     def isShah(self,color):
  388.         u""" color - цвет текущего короля
  389.            фун-я возращает находится ли король под шахом"""
  390.         korol = self.blackKorol if color == 'black' else self.whiteKorol
  391.         kotolpos = korol.pos
  392.         print kotolpos
  393.         vragcolor = vrag(color)
  394.         snap = self.boradSnapshoot()
  395.         for fig in [f for f in self if f.color == vragcolor]:
  396.             if kotolpos in fig.getPossibleMove(snap):
  397.                 return True
  398.         #posible =
  399.        
  400.     def run(self):
  401.         """ start game """
  402.        
  403.         hod = 'white'
  404.         curentfigure = None
  405.         lastfigure = None
  406.         lastpos = None
  407.         posiblemove = ()
  408.         while 1:
  409.             pygame.display.flip()
  410.             time.sleep(0.07)
  411.             # проверка на события пришедшее от пользователя
  412.             for event in pygame.event.get():
  413.                 if event.type == pygame.QUIT:
  414.                     sys.exit()
  415.                 elif event.type == 5 : #'mousebuttondown'
  416.                     # клик левой кн мыши
  417.                     if event.button == 1:
  418.                         curentpos = self.getpos(event.pos)
  419.                         curentfigure = self.getFigure(curentpos)
  420.                        
  421.                         # что то есть
  422.                         if  curentfigure:
  423.                             #уже есть выбранная фиг
  424.                             if lastfigure:
  425.                                 #  цвет такой же, меняем выбранную фиг  
  426.                                 if lastfigure.color == curentfigure.color:
  427.                                     lastfigure.pos = lastfigure.pos # перерисовываем предыдущую фиг и поле(убираем подсветку)
  428.                                     lastfigure = curentfigure
  429.                                    
  430.                                     #podsvetka !!!!
  431.                                     #self.redrawAll()
  432.                                     posiblemove = curentfigure.getPossibleMove(
  433.                                                           self.boradSnapshoot())
  434.                                                          
  435.                                     self.podsvetka(curentpos,posiblemove)                      
  436.                                                          
  437.                                     continue
  438.                                 # цвета разные, нужно рубить
  439.                                 else:
  440.                                     if curentpos not in posiblemove:
  441.                                         continue
  442.                                     self.killFigure(curentpos)
  443.                                     self.redrawAll()
  444.                                    
  445.                                     lastfigure.pos = curentpos
  446.                                     lastfigure = None
  447.                                     if self.isShah(vrag(hod)):
  448.                                         self.msg(u'%s шах %s'%(hod,vrag(hod)))
  449.                                     hod = vrag(hod)
  450.                             # прошлой нет        
  451.                             else:
  452.                                 if curentfigure.color == hod:
  453.                                     #self.podsvetka(curentpos)
  454.                                     lastfigure = curentfigure
  455.                                     posiblemove = curentfigure.getPossibleMove(
  456.                                                           self.boradSnapshoot())
  457.                                     self.podsvetka(curentpos,posiblemove)                      
  458.                                                          
  459.                         # клик по пустому полю  
  460.                         else:
  461.                             #фигура невыбрана- игнорируем
  462.                             if not lastfigure:continue
  463.                             # если ход возможен
  464.                             if curentpos not in posiblemove:
  465.                                         continue
  466.                             # иначе двигаем фигуру            
  467.                             self.redrawAll()
  468.                             lastfigure.pos = curentpos
  469.                             lastfigure = None # ссылка больше ненужна
  470.                             if self.isShah(vrag(hod)):
  471.                                         self.msg(u'%s шах %s'%(hod,vrag(hod)))
  472.                             hod = vrag(hod)
  473.                        
  474.             # отрисовка
  475.             pygame.display.flip()
  476.             time.sleep(0.07)                        
  477.                                
  478.      
  479. def vrag(color):
  480.     return  'black' if color != 'black' else 'white'
  481.    
  482.    
  483.    
  484. # запуск движка  pygame                            
  485. pygame.init()
  486. display = pygame.display.set_mode((480,480))
  487. pygame.display.set_caption(os.getcwd())      
  488.  
  489.  
  490.  
  491. if __name__ == '__main__':
  492.    
  493.          
  494.     a = Board()
  495.     a.startgame()
  496.     a.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement