Skip to content

Instantly share code, notes, and snippets.

@bowbahdoe
Created May 1, 2016 23:12
Show Gist options
  • Select an option

  • Save bowbahdoe/02c4eb6ce568a809091ee985a0d4e262 to your computer and use it in GitHub Desktop.

Select an option

Save bowbahdoe/02c4eb6ce568a809091ee985a0d4e262 to your computer and use it in GitHub Desktop.
'''
This defines an object to keep track of the game
This allows us to abstract the game logic from the rendering
'''
from board import Board
from key import Team
from key import Orientation
import enum
import itertools
class States(enum.Enum):
gold_play = 0
silver_play = 1
gold_respawning = 2
silver_respawning = 3
game_over = 4
gold_piece_selected = 5
silver_piece_selected = 6
class GameState(object):
'''
defines game actions and keeps track of the state of the game
'''
def __init__(self):
'''
Default constructor
'''
self._gameboard = Board.default_board()
self._state = States.gold_play
#_piece_selected is a location tuple or None
self._piece_selected = None
def is_a_team_respawning(self):
'''
returns True if a team is currently responding
'''
if self._state == States.gold_respawning:
return True
elif self._state == States.silver_respawning:
return True
else:
return False
def get_possible_moves_of_key(self, location):
'''
returns a list of tuples that represent the allowable moves of a key
at the given location
returns an empty list if there is no piece at the location
'''
piece = self._gameboard.get_piece_at_location(location)
if not piece:
return []
possible_moves = []
#we create a small lambda function depending on orientation of the key
#this says how we step through the locations of the board
if piece.orientation == Orientation.north:
stepper_function = lambda x, y: (x, y+1)
elif piece.orientation == Orientation.northeast:
stepper_function = lambda x, y: (x+1, y+1)
elif piece.orientation == Orientation.east:
stepper_function = lambda x, y: (x+1, y)
elif piece.orientation == Orientation.southeast:
stepper_function = lambda x, y: (x+1, y-1)
elif piece.orientation == Orientation.south:
stepper_function = lambda x, y: (x, y-1)
elif piece.orientation == Orientation.southwest:
stepper_function = lambda x, y: (x-1, y-1)
elif piece.orientation == Orientation.west:
stepper_function = lambda x, y: (x-1, y)
elif piece.orientation == Orientation.northwest:
stepper_function = lambda x, y: (x-1, y+1)
#uses 0 and 1 as indexes even though a location will usually
#have attributes accessable through loc.x and loc.y
possible_location = stepper_function(piece.location[0],
piece.location[1])
while self._gameboard.is_location_in_bounds(possible_location):
piece_at_location = self._gameboard.get_piece_at_location(location)
if not piece_at_location:
possible_moves.append(possible_location)
elif piece_at_location.team = piece.team
break
else:
possible_moves.append(possible_location)
break
possible_location = stepper_function(possible_location[0],
possible_location[1])
return possible_moves
def get_rotation_points_of_key(self, location):
'''
returns a list of tuples that represent the allowable rotation points
of a key at a given location
returns an empty list of there is no piece at the location
'''
piece = self._gameboard.get_piece_at_location(location)
if not piece:
return []
modifiers = (-1, 0, 1)
rotation_points = []
for x_modifier in modifiers:
for y_modifier in modifiers:
rotation_points.append((piece.location[0] + x_modifier,
piece.location[1] + y_modifier))
rotation_points = itertools.ifilter(self._gameboard.is_location_in_bounds,
rotation_points)
#we eliminate the possible moves from the rotation points
possible_moves = self.get_possible_moves_of_key(location)
rotation_points = [i for i in rotation_points if i not in possible_moves]
return rotation_points
def location_clicked(self, location):
'''
performs the proper action if a location is clicked
Will be a large method unless I can break it better
'''
#If we have a team playing then we allow for selecting a piece to move
if self._state == States.gold_play:
if self._gameboard.is_gold_piece_at_location(location):
self._piece_selected = location
self._state = States.gold_piece_selected
elif self._state == States.silver_play:
if self.is_silver_piece_at_location(location):
self._piece_selected = location
self._state = States.silver_piece_selected
#if a piece is selected already we have to handle moving
elif self._state == States.gold_piece_selected:
if location in self.get_possible_moves_of_key(self._piece_selected):
if self._gameboard.is_piece_at_location(location):
pass
if self._gameboard.is_locked_piece_at_location(location):
locked_piece = self._gameboard.get_piece_at_location(location)
else:
self._gameboard.move_piece_to_location()
else:
self._piece_selected = None
self._state = States.gold_play
elif self._state == States.silver_piece_selected:
pass
elif self._state == States.gold_respawning:
pass
elif self._state == States.silver_respawning:
pass
'''
implementation of the backend logic for the gameboard
This time the board is generic to the data type within, though
methods are still named in terms of keys
Also, the entire board is not stored, but intstead the coordinates
of pieces within as tuples of the form (x, y) along with the reference to
the data stored with it in a two dimensional list
The board width and height are also variable in order to accomodate possible
other board sizes
'''
from key import Key
from key import Team
from key import Orientation
class Board(object):
def __init__(self, width=8, height=8):
'''
default constructor, sets width and height of board
8x8 by default
'''
self.width = width
self.height = height
self._internal_board = {} #dict of unlocked keys
self._internal_lock_board = {} #dict of locked keys
def is_location_in_bounds(self, location):
'''
checks if the location is within the bounds of the board width and height
'''
#we do >= instead of > to accomodate zero indexing
if location[0] >= self.width:
return False
elif location[1] >= self.height:
return False
else:
return True
def set_piece_at_location(self, location, piece):
'''
sets the piece at a location
raises an error if it is out of bounds
'''
if self.is_location_in_bounds(location):
self._internal_board[location] = piece
else:
raise BufferError("location not within bounds of board")
def get_piece_at_location(self, location):
'''
gets a reference to the piece at the given location
returns None if there is no piece there
'''
try:
piece = self._internal_board[location]
return piece
except KeyError:
return None
def is_piece_at_location(self, location):
'''
Tells if a piece is at the given location
'''
if self.get_piece_at_location(location) == None:
return False
else:
return True
def is_locked_piece_at_location(self, location):
'''
Tells if a locked piece is at the given location
'''
if self.get_locked_piece_at_location(location) == None:
return False
else:
return True
def is_gold_piece_at_location(self, location):
'''
returns False if there is no piece at the location or if
the piece is of a different team
'''
piece = self.get_piece_at_location(location)
if piece: #if it exists
if piece.team == Team.gold:
return True
else:
return False
else:
return False
def is_silver_piece_at_location(self, location):
'''
returns False if there is no piece at the location or if
the piece is of a different team
'''
piece = self.get_piece_at_location(location)
if piece: #if it exists
if piece.team == Team.silver:
return True
else:
return False
else:
return False
def remove_piece_at_location(self, location):
'''
removes the piece at the given location
'''
try:
#tries to remove thi
self._internal_board.pop(location)
except KeyError:
#raised if piece not at location
raise KeyError("There is no piece at the given location
def lock_piece_at_location(self, location):
'''
Tries to lock the piece at the given location
'''
locked_piece = self._internal_board[location]
piece = self._internal_board[location]
def move_piece_to_location(self, location_1, location_2):
'''
Moves a piece from one location to another
Fails if there is no piece at location_1 or if there is a piece at
location_2
'''
if self.get_piece_at_location(location_2):
raise Exception("Key already at location_2")
if not self.get_piece_at_location(location_1):
raise Exception("No key at location_1")
@classmethod
def default_board(cls):
'''
alternate constructor
creates the default board with default piece placement
'''
self = cls()
piece_1 = Key(team = Team.gold,
orientation = Orientation.north)
piece_2 = Key(team = Team.gold,
orientation = Orientation.north)
piece_3 = Key(team = Team.gold,
orientation = Orientation.north)
piece_4 = Key(team = Team.silver,
orientation = Orientation.south)
piece_5 = Key(team = Team.silver,
orientation = Orientation.south)
piece_6 = Key(team = Team.silver,
orientation = Orientation.south)
pieces = [piece_1, piece_2, piece_3, piece_4, piece_5, piece_6]
locations = [(0,1), (0,3), (0,5), (7,2), (7,4), (7,6)]
for piece, location in zip(pieces, locations):
self.set_piece_at_location(location, piece)
return self
'''
contains the logic for the Key object
'''
import enum
class Orientation(enum.Enum):
'''
enum implementation of Key orientation
'''
north = 0
northeast = 1
east = 2
southeast = 3
south = 4
southwest = 5
west = 6
northwest = 7
class Team(enum.Enum):
'''
enum implementation of the team
'''
gold = 0
silver = 1
class Key(object):
def __init__(self,
team = Team.gold,
orientation = Orientation.north,
is_locked = False):
'''
default constructor, sets up a new key object
'''
self._team = team
self._orientation = orientation
self._is_locked = is_locked
def _get_is_locked(self):
'''
Hidden method
returns if the key is locked
'''
return self.is_locked
def _set_is_locked(self, is_locked):
'''
Hidden method
sets if the key is locked
is_locked is a bool
raises a TypeError if a bool is not passed
'''
if not isinstance(is_locked, bool):
raise TypeError("is_locked must be a bool")
self._is_locked = is_locked
def _get_team(self):
'''
Hidden method
returns the team of the key
'''
return self._team
def _set_team(self, new_team):
'''
Hidden method
sets the team of the key
raises a TypeError if a Team object is not passed
'''
if not isinstance(new_team, Team):
raise TypeError("Team must be an actual team")
else:
self._team = new_team
def _get_orientation(self):
'''
Hidden method
returns the orientation of the key
'''
return self._orientation
def _set_orientation(self, new_orientation):
'''
Hidden method
sets the orientation of the key
raises a TypeError if an Orientation object is not passed
'''
if not isinstance(new_orientation, Orientation):
raise TypeError("Orientation must be an actual orientation")
else:
self._orientation = new_orientation
team = property(fget = _get_team,
fset = _set_team)
orientation = property(fget = _get_orientation,
fset = _set_orientation)
is_locked = property(fget = _get_is_locked,
fset = _set_is_locked)
import Key
from Key import Key
class Board:
'''Begin the ugliest attempt at making the logic for a chess board in
the history of computer science'''
def __init__(self):
'''oh god here we go'''
self.board = [["A1",None,None],["A2",None,None],["A3",None,None],["A4",None,None],["A5",None,None],["A6",None,None],["A7",None,None],["A8",None,None],
["B1",None,None],["B2",None,None],["B3",None,None],["B4",None,None],["B5",None,None],["B6",None,None],["B7",None,None],["B8",None,None],
["C1",None,None],["C2",None,None],["C3",None,None],["C4",None,None],["C5",None,None],["C6",None,None],["C7",None,None],["C8",None,None],
["D1",None,None],["D2",None,None],["D3",None,None],["D4",None,None],["D5",None,None],["D6",None,None],["D7",None,None],["D8",None,None],
["E1",None,None],["E2",None,None],["E3",None,None],["E4",None,None],["E5",None,None],["E6",None,None],["E7",None,None],["E8",None,None],
["F1",None,None],["F2",None,None],["F3",None,None],["F4",None,None],["F5",None,None],["F6",None,None],["F7",None,None],["F8",None,None],
["G1",None,None],["G2",None,None],["G3",None,None],["G4",None,None],["G5",None,None],["G6",None,None],["G7",None,None],["G8",None,None],
["H1",None,None],["H2",None,None],["H3",None,None],["H4",None,None],["H5",None,None],["H6",None,None],["H7",None,None],["H8",None,None]]
#This deserves alot of explaination because it is the worst possible way to do this
#
#The board is a tuple of lists containing String objects in index[0] naming the location on the board
#
# 1|2|3|4|5|6|7|8
# _______________
# A|
# B|
# C|
# D|
# E|
# F|
# G|
# H|
#
#The second item in the list is any key object that may be on that location and if there is no key there it
#will have a None value
#
#The third item is for storing any locked keys
#otherwise it will be None
def reset(self):
for location in self.board:
location[2]=None
location[1]=None
self.setup()
def isGameOver(self):
silver = 0
gold = 0
for location in self.board:
unlockedPiece = location[1]
if(unlockedPiece)!=None:
if(unlockedPiece.getTeam()=="gold"):
gold+=1
else:
silver+=1
if gold == 0 or silver == 0:
return True
else:
return False
def _makeLocCartesian(self, Loc):
returner = []
locDic = {"A":1,"B":2,"C":3,"D":4,"E":5,"F":6,"G":7,"H":8}
returner.append(locDic[Loc[0]])
returner.append(int(Loc[1]))
return returner
def _makeLocAlphaNumeric(self,Loc):
locDic = {1:'A',2:'B',3:'C',4:'D',5:'E',6:'F',7:'G',8:'H'}
returner = ""
returner+=(locDic[Loc[0]])
returner+=str(Loc[1])
return returner
def _isLocOutOfBounds(self,loc):
'''loc is cartesian here'''
if loc[0] > 8 or loc[0] <1:
return True
if loc[1] > 8 or loc[1] <1:
return True
return False
def _findLocationIndexById(self,ID):
for square in self.board:
if square[0] == ID:
return self.board.index(square)
def movePieceToLocation(self,loc,piece):
lastLoc = piece.getLocation()
lastLocOnBoard = self._findLocationIndexById(lastLoc)
if self.isLockedPieceAtLocation(loc):
self.lockPieceAtLocation(loc)
self.board[lastLocOnBoard][1] = None
newLocOnBoard = self._findLocationIndexById(loc)
self.board[newLocOnBoard][1] = piece
piece.setLocation(loc)
def addPieceToLocation(self,loc,piece):
newLocOnBoard = self._findLocationIndexById(loc)
self.board[newLocOnBoard][1] = piece
piece.setLocation(loc)
def addLockedPieceToLocation(self,loc,piece):
piece.setLocked(True)
newLocOnBoard = self._findLocationIndexById(loc)
self.board[newLocOnBoard][2] = piece
piece.setLocation(loc)
def removePieceAtLocation(self,loc):
Loc = self._findLocationIndexById(loc)
self.board(Loc)[1] = None
def removeLockedPieceAtLocation(self,loc):
pass
def lockPieceAtLocation(self,loc):
Loc = self._findLocationIndexById(loc)
if self.board[Loc][1]!= None and self.board[2]==None:
self.board[Loc][2] = self.board[Loc][1]
self.board[Loc][1] = None
self.board[Loc][2].setLocked(True)
else:
pass
def unlockPieceAtLocation(self,loc):
#TODO make it so the piece is reset to a spawn point instead of
#just getting moved to the unlocked space
Loc = self._findLocationIndexById(loc)
if self.board[Loc][2]!= None:
self.board[Loc][2] = None
else:
pass
def isPieceAtLocation(self,loc):
loc = self._findLocationIndexById(loc)
if self.board[loc][1] != None:
return True
else:
return False
def isLockedPieceAtLocation(self,loc):
loc = self._findLocationIndexById(loc)
if self.board[loc][2] != None:
return True
else:
return False
def getPieceAtLocation(self,loc):
if type(loc) != str:
loc = self._makeLocAlphaNumeric(loc)
Loc = self._findLocationIndexById(loc)
if self.isPieceAtLocation(loc):
loc = self._findLocationIndexById(loc)
return self.board[loc][1]
else:
return None
def getLockedPieceAtLocation(self,loc):
if self.isLockedPieceAtLocation(loc):
loc = self._findLocationIndexById(loc)
return self.board[loc][2]
else:
pass
def getValidMovesOfKeyAtLoc(self,loc):
#This is the most complex and untested function
#So yeah, use with caution
key = self.getPieceAtLocation(loc)
if type(loc) == str:
loc = self._makeLocCartesian(loc)
done = False
returner = []
if key.getDirection() == "North":
oneabove = (loc[0]-1,loc[1])
while done == False:
if oneabove[0] <1:
done = True
elif self.getPieceAtLocation(oneabove) == None:
returner.append(oneabove)
oneabove = (oneabove[0]-1,oneabove[1])
elif self.getPieceAtLocation(oneabove).getTeam() != key.getTeam():
returner.append(oneabove)
done = True
else:
done = True
#done
elif key.getDirection() == "NorthWest":
upleft = (loc[0]-1,loc[1]-1)
while done==False:
if upleft[1]<1 or upleft[0]<1:
done = True
elif self.getPieceAtLocation(upleft) == None:
returner.append(upleft)
upleft = (upleft[0]-1 ,upleft[1]-1)
elif self.getPieceAtLocation(upleft).getTeam() != key.getTeam():
returner.append(upleft)
done = True
else:
done = True
elif key.getDirection() == "NorthEast":
upright = (loc[0]-1,loc[1]+1)
while done==False:
if upright[1]>8 or upright[0]<1:
done = True
elif self.getPieceAtLocation(upright) == None:
returner.append(upright)
upright = (upright[0]-1 ,upright[1]+1)
elif self.getPieceAtLocation(upright).getTeam() != key.getTeam():
returner.append(upright)
done = True
else:
done = True
elif key.getDirection() == "West":
oneleft = (loc[0] ,loc[1]-1)
while done == False:
if oneleft[1] <1:
done = True
elif self.getPieceAtLocation(oneleft) == None:
returner.append(oneleft)
oneleft = (oneleft[0] ,oneleft[1]-1)
elif self.getPieceAtLocation(oneleft).getTeam() != key.getTeam():
returner.append(oneleft)
done = True
else:
done = True
#look at place 1 to left
#if place x<8
#break
#if enemy piece there, add place
#break
#else
#if own piece there
#break
#if blank, add place
#goto Top
elif key.getDirection() == "SouthWest":
downleft = (loc[0]+1,loc[1]-1)
while done==False:
if downleft[1]<1 or downleft[0]>8:
done = True
elif self.getPieceAtLocation(downleft) == None:
returner.append(downleft)
downleft = (downleft[0]+1 ,downleft[1]-1)
elif self.getPieceAtLocation(downleft).getTeam() != key.getTeam():
returner.append(downleft)
done = True
else:
done = True
elif key.getDirection() == "South":
onebelow = (loc[0]+1,loc[1])
while done == False:
if onebelow[0] >8:
done = True
elif self.getPieceAtLocation(onebelow) == None:
returner.append(onebelow)
onebelow = (onebelow[0]+1,onebelow[1])
elif self.getPieceAtLocation(onebelow).getTeam() != key.getTeam():
returner.append(onebelow)
done = True
else:
done = True
elif key.getDirection() == "SouthEast":
downright = (loc[0]+1,loc[1]+1)
while done==False:
if downright[1]>8 or downright[0]>8:
done = True
elif self.getPieceAtLocation(downright) == None:
returner.append(downright)
downright = (downright[0]+1 ,downright[1]+1)
elif self.getPieceAtLocation(downright).getTeam() != key.getTeam():
returner.append(downright)
done = True
else:
done = True
elif key.getDirection() == "East":
oneright = (loc[0] ,loc[1] + 1)
while done == False:
if oneright[1] >8:
done = True
elif self.getPieceAtLocation(oneright) == None:
returner.append(oneright)
oneright = (oneright[0] ,oneright[1] + 1)
elif self.getPieceAtLocation(oneright).getTeam() != key.getTeam():
returner.append(oneright)
done = True
else:
done = True
return returner
def getDirectionIndicatedByRotatePoint(self,loc):
'''Seriosly, I need to do planning ahead before I
do anything important. I always end up with about 20 stupid
functions. Not-so-fun-ctions'''
if tuple(loc) == self.oneright:
return "East"
elif tuple(loc) == self.downright:
return "SouthEast"
elif tuple(loc) == self.onebelow:
return "South"
elif tuple(loc) == self.downleft:
return "SouthWest"
elif tuple(loc) == self.oneleft:
return "West"
elif tuple(loc) == self.upright:
return "NorthEast"
elif tuple(loc) == self.upleft:
return "NorthWest"
elif tuple(loc) == self.oneabove:
return "North"
def getRotatePointsofKeyAtLoc(self,loc):
key = self.getPieceAtLocation(loc)
if type(loc) == str:
loc = self._makeLocCartesian(loc)
done = False
returner = []
self.oneright = (loc[0] ,loc[1] + 1)
self.downright = (loc[0]+1,loc[1]+1)
self.onebelow = (loc[0]+1,loc[1])
self.downleft = (loc[0]+1,loc[1]-1)
self.oneleft = (loc[0] ,loc[1]-1)
self.upright = (loc[0]-1,loc[1]+1)
self.upleft = (loc[0]-1,loc[1]-1)
self.oneabove = (loc[0]-1,loc[1])
if key.getDirection() != "North":
returner.append(self.oneabove)
else: self.oneabove = None
if key.getDirection() != "East":
returner.append(self.oneright)
else: self.oneright = None
if key.getDirection() != "SouthEast":
returner.append(self.downright)
else: self.downright = None
if key.getDirection() != "South":
returner.append(self.onebelow)
else: self.onebelow = None
if key.getDirection() != "SouthWest":
returner.append(self.downleft)
else:
self.downleft = None
if key.getDirection() != "West":
returner.append(self.oneleft)
else:
self.oneleft = None
if key.getDirection() != "NorthEast":
returner.append(self.upright)
else:
self.upright = None
if key.getDirection() != "NorthWest":
returner.append(self.upleft)
else: self.upleft = None
for loc in returner:
if self._isLocOutOfBounds(loc):
returner.remove(loc)
return returner
def getFreeRespawnPointsForTeam(self,team):
gold = ["A2","A4","A6","A8"]
silver = ["H1","H3","H5","H7"]
returner = []
if team == "gold":
for loc in gold:
if self.getPieceAtLocation(loc) == None:
returner.append(loc)
if team == "silver":
for loc in silver:
if self.getPieceAtLocation(loc) == None:
returner.append(loc)
return returner
def setup(self):
'''This function, as of now, sets up the pieces how
we have them at the beggining of a game'''
gold1 = Key("A2","South",False,"gold")
gold2 = Key("A4","South",False,"gold")
gold3 = Key("A6","South",False,"gold")
self.addPieceToLocation("A2",gold1)
self.addPieceToLocation("A4",gold2)
self.addPieceToLocation("A6",gold3)
silver1 = Key("H3","North",False,"silver")
silver2 = Key("H5","North",False,"silver")
silver3 = Key("H7","North",False,"silver")
self.addPieceToLocation("H3",silver1)
self.addPieceToLocation("H5",silver2)
self.addPieceToLocation("H7",silver3)
#Copyright 2014 Ethan McCue
#All rights reserved to MacaulayCore
#import Board
try:
import pygame
except(ImportError):
import pyj2d as pygame
class Key:
def __init__(self,Location,Direction,isLocked,Team,selected=False):
self.Loc = Location
self.Dir = Direction
self.isLocked = isLocked
self.team = Team
self.isSelected = selected
if self.team == "gold":
self.baseTex = pygame.image.load("img/yellow1.png")
self.texture = pygame.image.load("img/yellow1.png")
else:
self.baseTex = pygame.image.load("img/silver1.png")
self.texture = pygame.image.load("img/silver1.png")
if self.team == "gold":
if self.Dir == "East":
self.texture =pygame.transform.rotate(self.baseTex,45)
if self.Dir == "SouthEast":
self.texture =pygame.transform.rotate(self.baseTex,360)
if self.Dir == "South":
self.texture =pygame.transform.rotate(self.baseTex,-40)
if self.Dir == "SouthWest":
self.texture =pygame.transform.rotate(self.baseTex,-90)
if self.Dir == "West":
self.texture =pygame.transform.rotate(self.baseTex,-135)
if self.Dir == "NorthWest":
self.texture =pygame.transform.rotate(self.baseTex,-180)
if self.Dir == "North":
self.texture =pygame.transform.rotate(self.baseTex,135)
if self.Dir == "NorthEast":
self.texture =pygame.transform.rotate(self.baseTex,90)
else:
if self.Dir == "East":
self.texture =pygame.transform.rotate(self.baseTex,-45)
if self.Dir == "SouthEast":
self.texture =pygame.transform.rotate(self.baseTex,-90)
if self.Dir == "South":
self.texture =pygame.transform.rotate(self.baseTex,-135)
if self.Dir == "SouthWest":
self.texture =pygame.transform.rotate(self.baseTex,-180)
if self.Dir == "West":
self.texture =pygame.transform.rotate(self.baseTex,135)
if self.Dir == "NorthWest":
self.texture =pygame.transform.rotate(self.baseTex,90)
if self.Dir == "North":
self.texture =pygame.transform.rotate(self.baseTex,45)
if self.Dir == "NorthEast":
self.texture =pygame.transform.rotate(self.baseTex,0)
self.frame = 1
def getLocation(self):
return self.Loc
def setLocation(self,Loc):
self.Loc = Loc
def getDirection(self):
return self.Dir
def setDirection(self,Dir):
self.Dir = Dir
if self.team == "gold":
if self.Dir == "East":
self.texture =pygame.transform.rotate(self.baseTex,45)
if self.Dir == "SouthEast":
self.texture =pygame.transform.rotate(self.baseTex,360)
if self.Dir == "South":
self.texture =pygame.transform.rotate(self.baseTex,-40)
if self.Dir == "SouthWest":
self.texture =pygame.transform.rotate(self.baseTex,-90)
if self.Dir == "West":
self.texture =pygame.transform.rotate(self.baseTex,-135)
if self.Dir == "NorthWest":
self.texture =pygame.transform.rotate(self.baseTex,-180)
if self.Dir == "North":
self.texture =pygame.transform.rotate(self.baseTex,135)
if self.Dir == "NorthEast":
self.texture =pygame.transform.rotate(self.baseTex,90)
else:
if self.Dir == "East":
self.texture =pygame.transform.rotate(self.baseTex,-45)
if self.Dir == "SouthEast":
self.texture =pygame.transform.rotate(self.baseTex,-90)
if self.Dir == "South":
self.texture =pygame.transform.rotate(self.baseTex,-135)
if self.Dir == "SouthWest":
self.texture =pygame.transform.rotate(self.baseTex,-180)
if self.Dir == "West":
self.texture =pygame.transform.rotate(self.baseTex,135)
if self.Dir == "NorthWest":
self.texture =pygame.transform.rotate(self.baseTex,90)
if self.Dir == "North":
self.texture =pygame.transform.rotate(self.baseTex,45)
if self.Dir == "NorthEast":
self.texture =pygame.transform.rotate(self.baseTex,0)
def isLocked(self):
return self.isLocked
def setLocked(self,locked):
'''True or False'''
if self.team=="gold":
self.texture = pygame.image.load("img/gold_lock.png")
else:
self.texture = pygame.image.load("img/silver_lock.png")
# self.texture = pygame.image.load("img/Black_Lock.png")
if locked:
self.isLocked = True
else:
self.isLocked = False
def getTeam(self):
return self.team
def setTeam(self,team):
if self.team == "gold":
self.texture = pygame.image.load("img/key-icon.png")
else:
self.texture = pygame.image.load("img/silver1.png")
def select(self):
if self.isSelected:
self.isSelected = False
else:
self.isSelected = True
def _makeLocCartesian(self, Loc):
returner = []
locDic = {"A":1,"B":2,"C":3,"D":4,"E":5,"F":6,"G":7,"H":8}
returner.append(locDic[Loc[0]])
returner.append(int(Loc[1]))
return returner
def _makeLocAlphaNumeric(self,Loc):
locDic = {1:'A',2:'B',3:'C',4:'D',5:'E',6:'F',7:'G',8:'H'}
returner = ""
returner+=(locDic[Loc[0]])
returner+=str(Loc[1])
return returner
def getTexture(self):
return self.texture
import sys
from time import sleep
from Board import Board
from Key import Key
from threading import Thread
try:
import pygame
from pygame.locals import *
JAVA = False
except(ImportError):
import pyj2d as pygame
from pyj2d.locals import *
JAVA = True
try:
import android
except(ImportError):
android = None
gameover = False
if android:
#(0,0) makes the display the size of the physical screen
#On android, we want this (varying resolutions, etc)
DISP = pygame.display.set_mode((0,0))
DISPLAYHEIGHT = DISP.get_size()[0];
DISPLAYWIDTH = DISP.get_size()[1];
else:
#These 2 need to be divisible by 8
DISPLAYHEIGHT = 600;
DISPLAYWIDTH = 600;
DISP = pygame.display.set_mode((DISPLAYHEIGHT,DISPLAYWIDTH))
SWIDTH = DISPLAYHEIGHT/8
SHEIGHT = DISPLAYWIDTH/8
FPS = 12
fpsclock = pygame.time.Clock()
SQUARESTOHIGHLIGHT = []
ROTATEPOINTS = []
RESPAWNPOINTS = []
class Respawn:
def __init__(self):
self.isRespawningNow = False
self.teamRespawning = None
def setRespawnOn(self,team):
self.teamRespawning = team
self.isRespawningNow = True
def setRespawnOff(self):
self.teamRespawning = None
self.isRespawningNow = False
def getIfRespawningNow(self):
return self.isRespawningNow
def getTeamRespawning(self):
return self.teamRespawning
class Turn:
def __init__(self):
self.turn = "gold"
self.pieceSelected = None
def getTurn(self):
return self.turn
def change(self):
if self.turn == "gold":
self.turn = "silver"
else:
self.turn ="gold"
def setSelected(self,loc):
self.pieceSelected = loc
def _makeLocCartesian(Loc):
returner = []
locDic = {"A":1,"B":2,"C":3,"D":4,"E":5,"F":6,"G":7,"H":8}
returner.append(locDic[Loc[0]])
returner.append(int(Loc[1]))
return returner
def _makeLocAlphaNumeric(Loc):
locDic = {1:'A',2:'B',3:'C',4:'D',5:'E',6:'F',7:'G',8:'H'}
returner = ""
returner+=(locDic[Loc[0]])
returner+=str(Loc[1])
return returner
def drawKeyAtLoc(DISP,key,loc):
if (key)!=None:
texture = key.getTexture()
loc = _makeLocCartesian(loc)
texture =pygame.transform.scale(texture,(DISPLAYHEIGHT/8,DISPLAYWIDTH/8))
DISP.blit(texture,(SWIDTH*(loc[1]-1),SHEIGHT*(loc[0]-1)))
def drawKeysOnBoard(DISP,Board):
x = ['A','B','C','D','E','F','G','H']
for i in x:
for e in range(8):
e+=1
loc = i+str(e)
key = Board.getPieceAtLocation(loc)
drawKeyAtLoc(DISP,key,loc)
def drawLockedKeysOnBoard(DISP,Board):
x = ['A','B','C','D','E','F','G','H']
for i in x:
for e in range(8):
e+=1
loc = i+str(e)
key = Board.getLockedPieceAtLocation(loc)
drawKeyAtLoc(DISP,key,loc)
def drawBoard(DisplayObj,color1=(0,0,0),color2=(100,100,100)):
black = color1
white = color2
DisplayObj.fill(black)
#Dont ask
#Just know it draws a chessboard
for i in range(7):
if i %2 == 0:
pygame.draw.rect(DisplayObj,white,(i*(DISPLAYHEIGHT/8),0,DISPLAYHEIGHT/8,DISPLAYWIDTH/8))
for i in range(8):
if i %2 != 0:
pygame.draw.rect(DisplayObj,white,(i*(DISPLAYHEIGHT/8),(DISPLAYWIDTH/8),DISPLAYHEIGHT/8,DISPLAYWIDTH/8))
for i in range(7):
if i %2 == 0:
pygame.draw.rect(DisplayObj,white,(i*(DISPLAYHEIGHT/8),(DISPLAYWIDTH/8)*2,DISPLAYHEIGHT/8,DISPLAYWIDTH/8))
for i in range(8):
if i %2 != 0:
pygame.draw.rect(DisplayObj,white,(i*(DISPLAYHEIGHT/8),(DISPLAYWIDTH/8)*3,DISPLAYHEIGHT/8,DISPLAYWIDTH/8))
for i in range(7):
if i %2 == 0:
pygame.draw.rect(DisplayObj,white,(i*(DISPLAYHEIGHT/8),(DISPLAYWIDTH/8)*4,DISPLAYHEIGHT/8,DISPLAYWIDTH/8))
for i in range(8):
if i %2 != 0:
pygame.draw.rect(DisplayObj,white,(i*(DISPLAYHEIGHT/8),(DISPLAYWIDTH/8)*5,DISPLAYHEIGHT/8,DISPLAYWIDTH/8))
for i in range(7):
if i %2 == 0:
pygame.draw.rect(DisplayObj,white,(i*(DISPLAYHEIGHT/8),(DISPLAYWIDTH/8)*6,DISPLAYHEIGHT/8,DISPLAYWIDTH/8))
for i in range(8):
if i %2 != 0:
pygame.draw.rect(DisplayObj,white,(i*(DISPLAYHEIGHT/8),(DISPLAYWIDTH/8)*7,DISPLAYHEIGHT/8,DISPLAYWIDTH/8))
def highlightSquare(loc,DisplayObj,color):
'''loc is a cartesian cordinate'''
RectHeight = DISPLAYHEIGHT/16
RectWidth = DISPLAYHEIGHT/16
x = loc[0]-1
y = loc[1]-1
pygame.draw.rect(DisplayObj,color,((x)*(SWIDTH),(SHEIGHT)*(y),SWIDTH,SHEIGHT),5)
#Drawing the outline of a square [The x coordinate to HL ] [The y coordinate to HL ]
#pygame.draw.rect(DisplayObj,color,((x)*(SWIDTH),(SHEIGHT)*(y),RectWidth,RectHeight)) #Leftline
#pygame.draw.rect(DisplayObj,color,((x)*(DISPLAYHEIGHT/8),(DISPLAYWIDTH/8)*(y),RectHeight,RectWidth)) #TopLine
#pygame.draw.rect(DisplayObj,color,
# (x*(DISPLAYHEIGHT/8),(((DISPLAYWIDTH/8)*(y+1))-(DISPLAYWIDTH/128)),DISPLAYHEIGHT/8,DISPLAYHEIGHT/128)) #<---broken, need to fix
#BottomLine^
#pygame.draw.rect(DisplayObj,color,
# ((((DISPLAYHEIGHT/8)*(loc[0]-1))+(DISPLAYHEIGHT/128)*18),(loc[1]-1)*(DISPLAYHEIGHT/8),DISPLAYWIDTH/128,DISPLAYHEIGHT/8)) #<---broken, need to fix
#TopLine
def handleKeyPress(event,turn,respawn):
shouldUpdate =1
a = respawn.isRespawningNow
z = getLocOfKeyPress(event)
tchange = False
lockedPieceAtDest = BOARD.getLockedPieceAtLocation(z)
unlockedPieceAtDest = BOARD.getPieceAtLocation(z)
if tuple(_makeLocCartesian(z)) in SQUARESTOHIGHLIGHT and not a:
if unlockedPieceAtDest!= None:
if unlockedPieceAtDest.getTeam() != BOARD.getPieceAtLocation(turn.pieceSelected).getTeam():
BOARD.addLockedPieceToLocation(z,unlockedPieceAtDest)
if lockedPieceAtDest != None:
if lockedPieceAtDest.getTeam() == BOARD.getPieceAtLocation(turn.pieceSelected).getTeam():
respawn.setRespawnOn(lockedPieceAtDest.getTeam())
#BOARD.unlockPieceAtLocation(z)
BOARD.movePieceToLocation(z,BOARD.getPieceAtLocation(turn.pieceSelected))
SQUARESTOHIGHLIGHT[:] =[]
ROTATEPOINTS[:] = []
tchange = True
elif tuple(_makeLocCartesian(z)) in ROTATEPOINTS and not a:
direc = BOARD.getDirectionIndicatedByRotatePoint(_makeLocCartesian(z))
piece = BOARD.getPieceAtLocation(turn.pieceSelected)
piece.setDirection(direc)
BOARD.addPieceToLocation(BOARD.getPieceAtLocation(turn.pieceSelected).getLocation(),
piece)
SQUARESTOHIGHLIGHT[:] =[]
ROTATEPOINTS[:] = []
tchange = True
elif BOARD.isPieceAtLocation(z) and BOARD.getPieceAtLocation(z).getTeam() == turn.getTurn() and not a:
turn.setSelected(z)
y = BOARD.getValidMovesOfKeyAtLoc(z)
y.sort()
SQUARESTOHIGHLIGHT.sort()
rotatePrelim = BOARD.getRotatePointsofKeyAtLoc(z)
if y != SQUARESTOHIGHLIGHT:
SQUARESTOHIGHLIGHT[:] =[]
ROTATEPOINTS[:] = []
for i in y:
remove = False
if i in SQUARESTOHIGHLIGHT:
SQUARESTOHIGHLIGHT.remove(i)
else:
SQUARESTOHIGHLIGHT.append(i)
highlightSquare((i[1],i[0]),DISP,(213,23,12))
for i in rotatePrelim:
if i in ROTATEPOINTS:
ROTATEPOINTS.remove(i)
else:
ROTATEPOINTS.append(i)
elif not a:
SQUARESTOHIGHLIGHT[:] = []
ROTATEPOINTS[:] = []
if respawn.isRespawningNow:
for i in BOARD.getFreeRespawnPointsForTeam(respawn.getTeamRespawning()):
if i not in RESPAWNPOINTS:
RESPAWNPOINTS.append(_makeLocCartesian(i))
if (_makeLocCartesian(z)) in RESPAWNPOINTS:
if respawn.getTeamRespawning() == "gold":
key = Key(z,"South",False,"gold")
BOARD.addPieceToLocation(z,key)
elif respawn.getTeamRespawning() == "silver":
key = Key(z,"North",False,"silver")
BOARD.addPieceToLocation(z,key)
RESPAWNPOINTS[:] = []
respawn.setRespawnOff()
for place in BOARD.board:
unlockedPiece = place[1]
lockedPiece = place[2]
if(not(unlockedPiece==None or lockedPiece==None)):
if(lockedPiece.getTeam()==unlockedPiece.getTeam()):
place[2] = None
if tchange:
turn.change()
def getLocOfKeyPress(event):
pos = [event.pos[0],event.pos[1]]
if JAVA:
pos = [event.pos[0]-3,event.pos[1]-25]
#if False:
# if x[0] >DISPLAYWIDTH:
# x[0] = DISPLAYWIDTH
#
#if x[1] > DISPLAYHEIGHT:
# x[1] = DISPLAYHEIGHT
returner = ""
print pos
#Alpha part
if pos[1] in range(SHEIGHT):
returner += "A"
elif pos[1] in range(((SHEIGHT)),(SHEIGHT)*2):
returner += "B"
elif pos[1] in range(((SHEIGHT)*2),(SHEIGHT)*3):
returner += "C"
elif pos[1] in range(((SHEIGHT)*3),(SHEIGHT)*4):
returner += "D"
elif pos[1] in range(((SHEIGHT)*4),(SHEIGHT)*5):
returner += "E"
elif pos[1] in range(((SHEIGHT)*5),(SHEIGHT)*6):
returner += "F"
elif pos[1] in range(((SHEIGHT)*6),(SHEIGHT)*7):
returner += "G"
elif pos[1] in range(((SHEIGHT)*7),(SHEIGHT)*8):
returner += "H"
#numeric Part
if pos[0] in range(SWIDTH):
returner += "1"
elif pos[0] in range(((SWIDTH)),(SWIDTH)*2):
returner += "2"
elif pos[0] in range(((SWIDTH)*2),(SWIDTH)*3):
returner += "3"
elif pos[0] in range(((SWIDTH)*3),(SWIDTH)*4):
returner += "4"
elif pos[0] in range(((SWIDTH)*4),(SWIDTH)*5):
returner += "5"
elif pos[0] in range(((SWIDTH)*5),(SWIDTH)*6):
returner += "6"
elif pos[0] in range(((SWIDTH)*6),(SWIDTH)*7):
returner += "7"
elif pos[0] in range(((SWIDTH)*7),(SWIDTH)*8):
returner += "8"
return returner
def resetGame():
print "resetting"
sleep(3)
BOARD.reset()
BOARD.isResetting= False
def drawGameOverScreen(Display,background=(0,0,0),winner="none"):
Display.fill((0,0,0))
try:
myfont = pygame.font.SysFont("monospace", 40)
label = myfont.render(winner +" has lost", 3, (DISP,0,0))
Display.blit(label, (SWIDTH, SHEIGHT))
except:
pass
fpsclock.tick(1)
pygame.display.update()
def main():
if android:
android.init()
android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)
respawn = Respawn()
turn = Turn()
background = pygame.Surface((DISPLAYHEIGHT,DISPLAYWIDTH))
drawBoard(background)
shouldUpdate = 1
pygame.init()
pygame.display.set_caption("Keys")
keys = pygame.Surface((DISPLAYHEIGHT,DISPLAYWIDTH))
drawKeysOnBoard(keys,BOARD)
DISP.blit(background,(0,0))
DISP.blit(keys,(0,0))
while True:
if android:
if android.check_pause():
android.wait_for_resume()
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == MOUSEBUTTONDOWN:
handleKeyPress(event,turn,respawn)
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
#for i in SQUARESTOHIGHLIGHT:
# highlightSquare((i[1],i[0]),DISP,(213,23,12))
shouldUpdate= 1
#pygame.display.update()
shouldUpdate=1
if shouldUpdate:
DISP.blit(background,(0,0))
drawLockedKeysOnBoard(DISP,BOARD)
drawKeysOnBoard(DISP,BOARD)
for i in ROTATEPOINTS:
highlightSquare((i[1],i[0]),DISP,(23,223,12))
for i in SQUARESTOHIGHLIGHT:
highlightSquare((i[1],i[0]),DISP,(213,23,12))
for i in RESPAWNPOINTS:
highlightSquare((i[1],i[0]),DISP,(233,34,223))
if BOARD.isGameOver():
#drawGameOverScreen(DISP,background,winner=turn.getTurn())
fpsclock.tick(1)
BOARD.reset()
#main()
print BOARD.isGameOver()
pygame.display.update()
fpsclock.tick(FPS)
BOARD = Board()
BOARD.setup()
shouldUpdate = 1
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment