Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # ver 4.1
- # date 13.4.2011
- # -*- coding:Utf-8 -*-
- import os,sys
- import pygame
- #from pygame.locals import *
- import time
- #MOUSEBUTTONDOWN
- WHITECOLOR = (190,190,210)
- BLACKCOLOR = (100,100,100)
- class ResManager(object):
- u"""Set data path and load image """
- #x = os.getcwd()
- def __init__(self, data_dir = '',
- image_dir = 'img'):
- self.data_dir = data_dir
- self.image_dir = image_dir
- def get_image(self, name):
- fullname = os.path.join(self.data_dir, os.path.join(self.image_dir, name))
- try:
- image = pygame.image.load(fullname)
- except pygame.error, message:
- return None
- else:
- image = image.convert_alpha()
- return image
- manager = ResManager( data_dir = '\\'.join((sys.argv[0].split('\\')[0:-1]))+'\\') #os.getcwd())
- class Figure(object):
- u"""parent calss """
- def __init__(self,pos =None,image=None,color = None):
- self.color = color
- image = manager.get_image(image)
- # если файл фигуры ненайден
- if not image and self.name:
- #self.font = pygame.font.Font(None, 24)
- self.font = pygame.font.SysFont('arial', 20)
- # в качестве картинки используем текст с именем фигуры
- image = self.font.render(' '+self.name, 0, {'black':(0,0,0),'white':(250,250,250)}[self.color])
- self.image = image
- self.pos = pos
- def posget(self):
- return self._posicion
- def moveAndDraw(self,val):
- 'clear kvadrat'
- if hasattr(self,'_posicion'):
- x,y = self._posicion
- d = 60
- if x%2 != y%2: col = BLACKCOLOR
- else: col = WHITECOLOR
- x1,y1 = x*d,y*d
- pygame.draw.polygon(display,col, ((x1,y1), (x1,y1+d), (x1+d,y1+d), (x1+d,y1) ))
- 'рисуем фигурку'
- self._posicion = val
- self.redraw()
- pos = property(posget, moveAndDraw)
- def redraw(self):
- x,y = self._posicion
- display.blit(self.image, (x*60,y*60))
- def clear(self):
- # закрасим после себя квадратик
- x,y = self._posicion
- d = 60
- if x%2 != y%2: col = BLACKCOLOR
- else: col = WHITECOLOR
- x1,y1 = x*d,y*d
- pygame.draw.polygon(display,col, ((x1,y1), (x1,y1+d), (x1+d,y1+d), (x1+d,y1) ))
- def snapshoot(self):
- return {self._posicion:self.color}
- def getPossibleMove(self,*k,**kw):
- raise Exception,'getPossibleMove method must be overridden in child'
- class WhitePeshka(Figure):
- name = u'пешка'
- def getPossibleMove(self,snap):
- posmov = []
- figx,figy = self._posicion
- if figy == 6: na4hod =3 # в начале пешка може ходить через клетку
- else: na4hod =2
- for y in xrange(1,na4hod):
- p = (figx, figy - y)
- if p in snap:
- break
- else:
- posmov.append(p)
- p = (figx+1,figy+1)
- if p in snap and snap[p] != self.color:
- posmov.append(p)
- p =(figx-1,figy+1)
- if p in snap and snap[p] != self.color:
- posmov.append(p)
- return posmov
- class BlackPeshka(Figure):
- name = u'пешка'
- def getPossibleMove(self,snap):
- posmov = []
- figx,figy = self._posicion
- if figy == 1: na4hod =3 # в начале пешка може ходить через клетку
- else: na4hod =2
- for y in xrange(1,na4hod):
- p = (figx,y + figy)
- if p in snap:
- break
- else:
- posmov.append(p)
- p = (figx+1,figy+1)
- if p in snap and snap[p] != self.color:
- posmov.append(p)
- p =(figx-1,figy+1)
- if p in snap and snap[p] != self.color:
- posmov.append(p)
- return posmov
- class Ladia(Figure):
- name = u'ладья'
- def getPossibleMove(self,snap):
- posmov = []
- figx,figy = self._posicion
- def generator():
- for g in (lambda: (figx, figy+x),
- lambda: (figx, figy-x),
- lambda: (figx+x, figy),
- lambda: (figx-x, figy)):
- yield g
- for foo in generator():
- for x in xrange(1,8):
- figpos = foo()
- if figpos in snap:
- if snap[figpos] != self.color:
- posmov.append(figpos)
- break
- else:
- posmov.append(figpos)
- return posmov
- class Kon(Figure):
- name = u'конь'
- def getPossibleMove(self,snap):
- posmov = []
- figx,figy = self._posicion
- for figpos in ((figx-1,figy+2),
- (figx-1,figy-2),
- (figx+1,figy+2),
- (figx+1,figy-2),
- (figx-2,figy+1),
- (figx-2,figy-1),
- (figx+2,figy+1),
- (figx+2,figy-1)):
- if figpos in snap:
- if snap[figpos] != self.color:
- posmov.append(figpos)
- else:
- posmov.append(figpos)
- return posmov
- class Slon(Figure):
- name = u'слон'
- def getPossibleMove(self,snap):
- posmov = []
- figx,figy = self._posicion
- def generator():
- for g in (lambda: (figx+x, figy+x),
- lambda: (figx-x, figy-x),
- lambda: (figx+x, figy-x),
- lambda: (figx-x, figy+x)):
- yield g
- for foo in generator():
- for x in xrange(1,8):
- figpos = foo()
- if figpos in snap:
- if snap[figpos] != self.color:
- posmov.append(figpos)
- break
- else:
- posmov.append(figpos)
- return posmov
- class Ferz(Figure):
- name = u'ферзь'
- def getPossibleMove(self,snap):
- posmov = []
- figx,figy = self._posicion
- def generator():
- for g in (lambda: (figx+x, figy+x),
- lambda: (figx-x, figy-x),
- lambda: (figx+x, figy-x),
- lambda: (figx-x, figy+x),
- lambda: (figx, figy+x),
- lambda: (figx, figy-x),
- lambda: (figx+x, figy),
- lambda: (figx-x, figy)):
- yield g
- for foo in generator():
- for x in xrange(1,8):
- figpos = foo()
- if figpos in snap:
- if snap[figpos] != self.color:
- posmov.append(figpos)
- break
- else:
- posmov.append(figpos)
- return posmov
- class Korol(Figure):
- name = u'король'
- def getPossibleMove(self,snap):
- posmov = []
- figx,figy = self._posicion
- for figpos in ( (figx-1,figy+1),
- (figx-1,figy-1),
- (figx+1,figy+1),
- (figx+1,figy-1),
- (figx,figy+1),
- (figx,figy-1),
- (figx+1,figy),
- (figx-1,figy)):
- if figpos in snap:
- if snap[figpos] != self.color:
- posmov.append(figpos)
- else:
- posmov.append(figpos)
- return posmov
- class Singleton(type):
- def __init__(cls, name, bases, dict):
- super(Singleton, cls).__init__(name, bases, dict)
- cls.instance = None
- def __call__(cls,*args,**kw):
- if cls.instance is None:
- cls.instance = super(Singleton, cls).__call__(*args, **kw)
- return cls.instance
- class Board(list):
- u"""класс реализует контейнер для фигур"""
- __metaclass__ = Singleton
- # перегрузим + чтоб меньше писать потом
- def __add__(self,val):
- self.append(val)
- def drawboard(self,curentfigure= None):
- u""" рисуем клетки """
- display.fill(WHITECOLOR)
- d = 60
- for x in xrange(0,8):
- for y in xrange(0,8):
- if x%2 != y%2:
- x1,y1 = x*d,y*d
- pygame.draw.polygon(display, BLACKCOLOR, ((x1,y1), (x1,y1+d), (x1+d,y1+d), (x1+d,y1) ))
- if curentfigure:
- self._drawcurentfigure(display,curentfigure,linecolor = (10,200,10))
- def getpos(self,mousexy):
- return mousexy[0]/60,mousexy[1]/60
- def getFigure(self,pos) :
- x,y = pos
- if 0>x or x>7 or 0>y or y>7:return None
- for fig in self:
- if fig and fig.pos == pos: return fig
- def killFigure(self,pos):
- for x in xrange(len(self)):
- fig = self[x]
- if fig and fig.pos == pos:
- fig.clear()
- del self[x]
- return
- def initFigure(self):
- for x in xrange(8):
- self + BlackPeshka(pos = (x,1),color = 'black',image='bp.png' )
- self + WhitePeshka(pos = (x,6),color = 'white',image='wp.png')
- self + Ladia(pos = (0,7), color = 'white',image= 'wl.png')
- self + Ladia(pos = (7,7), color = 'white',image= 'wl.png')
- self + Kon(pos = (1,7), color = 'white',image= 'wkon.png')
- self + Kon(pos = (6,7), color = 'white',image= 'wkon.png')
- self + Slon(pos = (2,7), color = 'white',image= 'ws.png')
- self + Slon(pos = (5,7), color = 'white',image= 'ws.png')
- self + Ferz(pos = (3,7), color = 'white',image= 'wf.png')
- self.whiteKorol = Korol(pos = (4,7), color = 'white',image= 'wk.png')
- self + self.whiteKorol
- self + Ladia(pos = (0,0), color = 'black',image= 'bl.png')
- self + Ladia(pos = (7,0), color = 'black',image= 'bl.png')
- self + Kon(pos = (1,0),color = 'black',image= 'bkon.png')
- self + Kon(pos = (6,0),color = 'black',image= 'bkon.png')
- self + Slon(pos = (2,0), color = 'black',image= 'bs.png')
- self + Slon(pos = (5,0),color = 'black',image='bs.png')
- self + Ferz(pos = (3,0),color = 'black',image= 'bf.png')
- self.blackKorol = Korol(pos = (4,0),color = 'black',image= 'bk.png')
- self + self.blackKorol
- def startgame(self):
- u"""restart game, set default pos figure and vars"""
- self.drawboard()
- #self.board.initFigure(self.manager)
- self.initFigure()
- pygame.display.flip()
- def redrawAll(self):
- self.drawboard()
- for fig in self:
- fig.redraw()
- def podsvetka(self,pos,posiblemove):
- self.redrawAll()
- linecolor = (30,30,50)
- x,y = pos
- d = 60
- x1,y1 = x*d,y*d
- #pygame.draw.circle(display,(255,10,0), (x1+30,y1+30), 3)
- self._drawcurentfigure(pos,linecolor = (0,10,200))
- for kletka in posiblemove:
- self._drawcurentfigure(kletka,linecolor = (0,210,20))
- def _drawcurentfigure(self,curentfigure,linecolor = None):
- u"""выделяем выбраную фигуру """
- x,y = curentfigure
- d = 60
- x1,y1 = x*d,y*d
- w = 3 # ширина линии подсветки
- dx = 3 # смещение во внутрь
- pygame.draw.line(display, linecolor, (x1+dx,y1+dx ), (x1+d-dx,y1+dx ),w)
- pygame.draw.line(display, linecolor, (x1+dx,y1+dx ), (x1+dx,y1+d-dx ),w)
- pygame.draw.line(display, linecolor, (x1+d-dx,y1+d-dx), (x1+d-dx,y1+dx ),w)
- pygame.draw.line(display, linecolor, (x1+dx,y1+d-dx ), (x1+d-dx,y1+d-dx),w)
- pygame.draw.circle(display,linecolor, (x1+30,y1+30), 3)
- def boradSnapshoot(self):
- out = {}
- for fig in self:
- out.update(fig.snapshoot())
- return out
- def msg(self,text):
- for x in range(0,55):
- font = pygame.font.SysFont('arial', 50+x/2)
- image = font.render(text, 100, (4*x,4*x,1*x))
- display.blit(image, (90-x,210))
- pygame.display.flip()
- time.sleep(0.011)
- def isShah(self,color):
- u""" color - цвет текущего короля
- фун-я возращает находится ли король под шахом"""
- korol = self.blackKorol if color == 'black' else self.whiteKorol
- kotolpos = korol.pos
- print kotolpos
- vragcolor = vrag(color)
- snap = self.boradSnapshoot()
- for fig in [f for f in self if f.color == vragcolor]:
- if kotolpos in fig.getPossibleMove(snap):
- return True
- #posible =
- def run(self):
- """ start game """
- hod = 'white'
- curentfigure = None
- lastfigure = None
- lastpos = None
- posiblemove = ()
- while 1:
- pygame.display.flip()
- time.sleep(0.07)
- # проверка на события пришедшее от пользователя
- for event in pygame.event.get():
- if event.type == pygame.QUIT:
- sys.exit()
- elif event.type == 5 : #'mousebuttondown'
- # клик левой кн мыши
- if event.button == 1:
- curentpos = self.getpos(event.pos)
- curentfigure = self.getFigure(curentpos)
- # что то есть
- if curentfigure:
- #уже есть выбранная фиг
- if lastfigure:
- # цвет такой же, меняем выбранную фиг
- if lastfigure.color == curentfigure.color:
- lastfigure.pos = lastfigure.pos # перерисовываем предыдущую фиг и поле(убираем подсветку)
- lastfigure = curentfigure
- #podsvetka !!!!
- #self.redrawAll()
- posiblemove = curentfigure.getPossibleMove(
- self.boradSnapshoot())
- self.podsvetka(curentpos,posiblemove)
- continue
- # цвета разные, нужно рубить
- else:
- if curentpos not in posiblemove:
- continue
- self.killFigure(curentpos)
- self.redrawAll()
- lastfigure.pos = curentpos
- lastfigure = None
- if self.isShah(vrag(hod)):
- self.msg(u'%s шах %s'%(hod,vrag(hod)))
- hod = vrag(hod)
- # прошлой нет
- else:
- if curentfigure.color == hod:
- #self.podsvetka(curentpos)
- lastfigure = curentfigure
- posiblemove = curentfigure.getPossibleMove(
- self.boradSnapshoot())
- self.podsvetka(curentpos,posiblemove)
- # клик по пустому полю
- else:
- #фигура невыбрана- игнорируем
- if not lastfigure:continue
- # если ход возможен
- if curentpos not in posiblemove:
- continue
- # иначе двигаем фигуру
- self.redrawAll()
- lastfigure.pos = curentpos
- lastfigure = None # ссылка больше ненужна
- if self.isShah(vrag(hod)):
- self.msg(u'%s шах %s'%(hod,vrag(hod)))
- hod = vrag(hod)
- # отрисовка
- pygame.display.flip()
- time.sleep(0.07)
- def vrag(color):
- return 'black' if color != 'black' else 'white'
- # запуск движка pygame
- pygame.init()
- display = pygame.display.set_mode((480,480))
- pygame.display.set_caption(os.getcwd())
- if __name__ == '__main__':
- a = Board()
- a.startgame()
- a.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement