Pastebin
API
tools
faq
paste
Login
Sign up
Please fix the following errors:
New Paste
Syntax Highlighting
# 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()
Optional Paste Settings
Category:
None
Cryptocurrency
Cybersecurity
Fixit
Food
Gaming
Haiku
Help
History
Housing
Jokes
Legal
Money
Movies
Music
Pets
Photo
Science
Software
Source Code
Spirit
Sports
Travel
TV
Writing
Tags:
Syntax Highlighting:
None
Bash
C
C#
C++
CSS
HTML
JSON
Java
JavaScript
Lua
Markdown (PRO members only)
Objective C
PHP
Perl
Python
Ruby
Swift
4CS
6502 ACME Cross Assembler
6502 Kick Assembler
6502 TASM/64TASS
ABAP
AIMMS
ALGOL 68
APT Sources
ARM
ASM (NASM)
ASP
ActionScript
ActionScript 3
Ada
Apache Log
AppleScript
Arduino
Asymptote
AutoIt
Autohotkey
Avisynth
Awk
BASCOM AVR
BNF
BOO
Bash
Basic4GL
Batch
BibTeX
Blitz Basic
Blitz3D
BlitzMax
BrainFuck
C
C (WinAPI)
C Intermediate Language
C for Macs
C#
C++
C++ (WinAPI)
C++ (with Qt extensions)
C: Loadrunner
CAD DCL
CAD Lisp
CFDG
CMake
COBOL
CSS
Ceylon
ChaiScript
Chapel
Clojure
Clone C
Clone C++
CoffeeScript
ColdFusion
Cuesheet
D
DCL
DCPU-16
DCS
DIV
DOT
Dart
Delphi
Delphi Prism (Oxygene)
Diff
E
ECMAScript
EPC
Easytrieve
Eiffel
Email
Erlang
Euphoria
F#
FO Language
Falcon
Filemaker
Formula One
Fortran
FreeBasic
FreeSWITCH
GAMBAS
GDB
GDScript
Game Maker
Genero
Genie
GetText
Go
Godot GLSL
Groovy
GwBasic
HQ9 Plus
HTML
HTML 5
Haskell
Haxe
HicEst
IDL
INI file
INTERCAL
IO
ISPF Panel Definition
Icon
Inno Script
J
JCL
JSON
Java
Java 5
JavaScript
Julia
KSP (Kontakt Script)
KiXtart
Kotlin
LDIF
LLVM
LOL Code
LScript
Latex
Liberty BASIC
Linden Scripting
Lisp
Loco Basic
Logtalk
Lotus Formulas
Lotus Script
Lua
M68000 Assembler
MIX Assembler
MK-61/52
MPASM
MXML
MagikSF
Make
MapBasic
Markdown (PRO members only)
MatLab
Mercury
MetaPost
Modula 2
Modula 3
Motorola 68000 HiSoft Dev
MySQL
Nagios
NetRexx
Nginx
Nim
NullSoft Installer
OCaml
OCaml Brief
Oberon 2
Objeck Programming Langua
Objective C
Octave
Open Object Rexx
OpenBSD PACKET FILTER
OpenGL Shading
Openoffice BASIC
Oracle 11
Oracle 8
Oz
PARI/GP
PCRE
PHP
PHP Brief
PL/I
PL/SQL
POV-Ray
ParaSail
Pascal
Pawn
Per
Perl
Perl 6
Phix
Pic 16
Pike
Pixel Bender
PostScript
PostgreSQL
PowerBuilder
PowerShell
ProFTPd
Progress
Prolog
Properties
ProvideX
Puppet
PureBasic
PyCon
Python
Python for S60
QBasic
QML
R
RBScript
REBOL
REG
RPM Spec
Racket
Rails
Rexx
Robots
Roff Manpage
Ruby
Ruby Gnuplot
Rust
SAS
SCL
SPARK
SPARQL
SQF
SQL
SSH Config
Scala
Scheme
Scilab
SdlBasic
Smalltalk
Smarty
StandardML
StoneScript
SuperCollider
Swift
SystemVerilog
T-SQL
TCL
TeXgraph
Tera Term
TypeScript
TypoScript
UPC
Unicon
UnrealScript
Urbi
VB.NET
VBScript
VHDL
VIM
Vala
Vedit
VeriLog
Visual Pro Log
VisualBasic
VisualFoxPro
WHOIS
WhiteSpace
Winbatch
XBasic
XML
XPP
Xojo
Xorg Config
YAML
YARA
Z80 Assembler
ZXBasic
autoconf
jQuery
mIRC
newLISP
q/kdb+
thinBasic
Paste Expiration:
Never
Burn after read
10 Minutes
1 Hour
1 Day
1 Week
2 Weeks
1 Month
6 Months
1 Year
Paste Exposure:
Public
Unlisted
Private
Folder:
(members only)
Password
NEW
Enabled
Disabled
Burn after read
NEW
Paste Name / Title:
Create New Paste
Hello
Guest
Sign Up
or
Login
Sign in with Facebook
Sign in with Twitter
Sign in with Google
You are currently not logged in, this means you can not edit or delete anything you paste.
Sign Up
or
Login
Public Pastes
Make 3500$ in 20 MIN [Method] R
JavaScript | 3 sec ago | 0.08 KB
1500$ in 1 day [Method]? MA
Java | 3 sec ago | 0.05 KB
Make $2500 in 15 minutes E
JavaScript | 21 sec ago | 0.08 KB
Make 3500$ in 20 MIN [Method] P
JavaScript | 23 sec ago | 0.08 KB
✅ MAKE $22OO IN 10 MIN Q
JavaScript | 34 sec ago | 0.08 KB
Make 3500$ in 1 day [Method]XH
Java | 45 sec ago | 0.06 KB
MAKE $5000 INSTANTLY Y
JavaScript | 1 min ago | 0.08 KB
Make $2500 in 15 minutes 9
JavaScript | 1 min ago | 0.08 KB
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the
Cookies Policy
.
OK, I Understand
Not a member of Pastebin yet?
Sign Up
, it unlocks many cool features!