def __init__(self): pygame.init() self.game_settings = GameSettings() self.board_settings = BoardSettings() self.logo = pygame.image.load('assets/logo.png') pygame.display.set_icon(self.logo) pygame.display.set_caption("{} Version: {}".format( self.game_settings.name, self.game_settings.version)) self.board = Board() self.screen = self.board.drawBoard() self.clock = pygame.time.Clock() self.green_set = JanggiSet(self, 'Green', 'assets/green_pieces.png', 'assets/green_pieces.json') self.red_set = JanggiSet(self, 'Red', 'assets/red_pieces.png', 'assets/red_pieces.json') # mouse tracker self.mouseDown = False self.mouseReleased = False self.grabbed_piece = None self.moveList = [] # player turn self.turn = "Red"
def main(board_size, number_of_dice): player_list, snake_list, ladder_list = parse_input_file() board_object = Board(board_size, player_list, snake_list, ladder_list, number_of_dice) # stop when one player wins # can be extended to playing game till one player exists by changing to # while board_object.get_number_of_winner() != len(player_list)-1: while board_object.get_number_of_winner() == 0: _dice_val, _source, _player = board_object.make_move() print(str(_player.get_name()) + " rolled a " + str(_dice_val) + " and moved from " + str(_source) + " to " + str(_player.get_current_pos())) _rank_list = board_object.get_rank_list() for key, val in _rank_list.items(): print(key.get_name() + " wins the game")
def __init__(self,config): Board.__init__(self,config.BOARD_WIDTH,config.BOARD_HEIGHT) self.config = config with open("names.txt") as namesFile: self._namesList = [line.replace("\n","") for line in namesFile.readlines()] shuffle(self._namesList) initialDNAString = config.INITIAL_DNA if initialDNAString: startDNA = [actions.DNA_MAP[char] for char in initialDNAString.upper()] else: startDNA = list(actions.ALL_ACTIONS) # Copy the list shuffle(startDNA) totalMonsters = 0 totalFood = 0 for x in range(self.width): for y in range(self.height): if probcheck() < config.MONSTER_DENSITY and totalMonsters < config.MAX_NUM_MONSTERS: self[x,y] = Monster(startDNA, config.INITIAL_HP, config.INITIAL_COLOR) totalMonsters += 1 elif probcheck() < config.FOOD_DENSITY and totalFood < config.MAX_NUM_FOOD: self[x,y] = FOOD totalFood += 1
def __init__(self): super().__init__() self.title('Chess V2') if sys.platform == "linux": self.window_arg = "-zoomed" else: self.window_arg = "-fullscreen" self.fullscreen_state = False self.attributes(self.window_arg, self.fullscreen_state) self.bind("<F11>", self.toggle_fullscreen) self.bind("<Escape>", self.exit_fullscreen) self.board = Board(self) self.mainloop()
def launchGame(): pieceSize = 100 # taille de chaque pièce du jeu d'échecs pygame.init() #* ================== Window ===================== WIDTH, HEIGHT = 1000, 1000 # Largeur et hauteur de la fenêtre WIN = pygame.display.set_mode((WIDTH, HEIGHT)) # Définir la fenêtre pygame.display.set_caption("Chess") # Titre de la fenêtre main_font = pygame.font.SysFont("comicsans", 50) end_game_font = pygame.font.SysFont("comicsans", 75) board = Board() playerWhite = Player(board, WHITE) playerBlack = Player(board, BLACK) #* Register register = Register(settings["whereToSave"], settings["whoPlaysWhite"], settings["whoPlaysBlack"]) def endGame(whoWins): """ Affiche la fin de la game si victoire de l'un """ textsurface = end_game_font.render(f'{whoWins} WINS', True, Color.BLUE.value) WIN.blit(textsurface, (400,400)) pygame.display.update() duration = 0 while duration < 10000: for event in pygame.event.get(): if event.type == pygame.QUIT: exit() pygame.time.delay(50) duration += 50 exit() def endGameNulle() : """ Affiche la fin d'une partie en cas de pat (match nul) """ textsurface = end_game_font.render(f'NULLE', True, Color.BLUE.value) WIN.blit(textsurface, (400,400)) pygame.display.update() duration = 0 while duration < 10000: for event in pygame.event.get(): if event.type == pygame.QUIT: exit() pygame.time.delay(50) duration += 50 exit() nbCoups = 0 while True: board.updateGraphicalInterface(WIN, [playerBlack, playerWhite]) # print(board) nbCoups+=1 # On incrémente le nombre de coups etat = playerWhite.turn(board, playerBlack, WIN, nbCoups, register) # Tour des blancs if etat == 0: # Les blancs ont perdu endGame('BLACK') elif etat == 1: endGameNulle() # print() # print("\n".join([str(x) for x in playerBlack.king.casesInaccessiblesPourLeRoi(board, playerWhite)])) # print() nbCoups+=1 # on incrémente de coups etat = playerBlack.turn(board, playerWhite, WIN, nbCoups, register) # Tour des noirs if etat == 0: # Les noirs ont perdu endGame('WHITE') elif etat == 1: endGameNulle() for event in pygame.event.get(): if event.type == pygame.QUIT: return
def main(): # get PCBmodE version version = utils.get_git_revision() # setup and parse commandline arguments argp = cmdArgSetup(version) cmdline_args = argp.parse_args() # Might support running multiple boards in the future, # for now get the first onw board_name = cmdline_args.boards[0] makeConfig(board_name, version, cmdline_args) # check if build directory exists; if not, create build_dir = os.path.join(config.cfg['base-dir'], config.cfg['locations']['build']) utils.create_dir(build_dir) # renumber refdefs and dump board config file if cmdline_args.renumber is not False: msg.info("Renumbering refdefs") if cmdline_args.renumber is None: order = 'top-to-bottom' else: order = cmdline_args.renumber.lower() utils.renumberRefdefs(order) # Extract routing from input SVG file elif cmdline_args.extract is True: extract.extract() # Create a BoM elif cmdline_args.make_bom is not False: bom.make_bom(cmdline_args.make_bom) else: # make the board if cmdline_args.make is True: msg.info("Creating board") board = Board() # Create production files (Gerbers, Excellon, etc.) if cmdline_args.fab is not False: if cmdline_args.fab is None: manufacturer = 'default' else: manufacturer = cmdline_args.fab.lower() msg.info("Creating Gerbers") gerber.gerberise(manufacturer) msg.info("Creating excellon drill file") excellon.makeExcellon(manufacturer) if cmdline_args.pngs is True: msg.info("Creating PNGs") utils.makePngs() filename = os.path.join(config.cfg['locations']['boards'], config.cfg['name'], config.cfg['locations']['build'], 'paths_db.json') try: f = open(filename, 'wb') except IOError as e: print "I/O error({0}): {1}".format(e.errno, e.strerror) f.write(json.dumps(config.pth, sort_keys=True, indent=2)) f.close() msg.info("Done!")
from utils.pieces import Piece from utils.board import Board from utils.teams import Team from termcolor import colored from utils.helper import (y_flip, get_x_between, get_y_between, letter_to_number, number_to_letter, print_error, get_piece_to_move, get_target_position, update_team_threat, checkmate, get_between_exclusive, check_move) board = Board() def player_move(team, oppo_team): print(colored(team.colour + '\'s turn', team.colour)) curr_pos = get_piece_to_move() tar_pos = get_target_position() result = check_move(team, oppo_team, curr_pos, tar_pos, board) return result, curr_pos, tar_pos def act_on_result(result, curr_pos, tar_pos, team): """ Takes result of player_move and check_move functions to determine next action Return: 0 if move is invalid (same player's turn) 1 if move is valid (next player's turn)
def play_a_game(settings, snakes_and_ladders=False, report_frequency='end'): """ Takes input settings and plays a game. Outputs the final configuration of the game. :param settings: A dict containing all the information loaded from a json file :param snakes_and_ladders: Optional arg. If blank, will just use the snakes and ladders from the settings, if not, will use the configuration supplied. :param report_frequency: Choice for frequency of reports. Options are: 'end' for end of game, and 'turn' for a report every turn. :return: A generated report on the matter """ if snakes_and_ladders: settings['board']['snakes_and_ladders'] = snakes_and_ladders b = Board(**settings['board']) for i in range(settings['players']['number_of_players']): p = BasePlayer("ai{}".format(i)) b.add_player(p) if report_frequency == 'end': while not b.check_for_winners(): b.take_turn() final_report = b.generate_report() elif report_frequency == 'turn': final_report = dict() while not b.check_for_winners(): t = b.get_number_of_turns() r = b.generate_report() final_report[t] = r b.take_turn() t = b.get_number_of_turns() r = b.generate_report() final_report[t] = r else: raise ValueError('{} is not a valid input'.format(report_frequency)) return final_report
from utils.engine import Engine if __name__ == '__main__': size = input("Entrez la taille du plateau (inf à 26 et pair): ") while not size.isdigit() \ or int(size) < 4 or int(size) > 26 \ or int(size) % 2 == 1: size = input("Err, entrez la taille du plateau (inf à 26 et pair): ") width = height = int(size) players = input("Joueur contre une IA ? [O/n] ") while players.lower() not in [ 'yes', 'y', 'oui', 'o', 'no', 'n', 'non', '' ]: players = input("Err, joueur contre une IA ? [O/n] ") players = 2 if players in ['no', 'n', 'non'] else 1 board = Board(width, height) board.make_board() engine = Engine(board, players) engine.start() try: while engine.is_playing: engine.get_action() except (KeyboardInterrupt, EOFError): engine.stop()
def main(): pygame.init() clock_object = pygame.time.Clock() game_settings = Settings() lines = Borders(game_settings) # initialize screen size screen = pygame.display.set_mode((game_settings.screen_width, game_settings.screen_height)) pygame.display.set_caption("2048") # Create game instance and add three cells to it. game_board = Board(game_settings, screen) game_board.add_tile(game_settings, quantity=3) while True: # Limits screen refreshment speed. clock_object.tick(30) game_board.draw_board(game_settings) lines.draw_lines(screen, game_settings) for event in pygame.event.get(): if event.type == pygame.QUIT: # If game window is closed. sys.exit() elif event.type == pygame.KEYDOWN: # If keyboard keys are pressed. if event.key in game_board.movement_keys: # New tile is added only if key press initiated a change in game board. # If move() or calculate() returns True, then cell value was modified, and new tile is added. change_in_move_1 = game_board.move(event.key, game_settings) change_in_calculate = game_board.calculate(event.key, game_settings) change_in_move_2 = game_board.move(event.key, game_settings) if change_in_move_1 or change_in_move_2 or change_in_calculate: game_board.add_tile(game_settings, quantity=1) elif game_board.check_game_over(game_settings): game_board.game_over(game_settings) elif event.key == pygame.K_q: sys.exit() pygame.display.flip()
class JanggiGame: """ Main class that starts the game. """ def __init__(self): pygame.init() self.game_settings = GameSettings() self.board_settings = BoardSettings() self.logo = pygame.image.load('assets/logo.png') pygame.display.set_icon(self.logo) pygame.display.set_caption("{} Version: {}".format( self.game_settings.name, self.game_settings.version)) self.board = Board() self.screen = self.board.drawBoard() self.clock = pygame.time.Clock() self.green_set = JanggiSet(self, 'Green', 'assets/green_pieces.png', 'assets/green_pieces.json') self.red_set = JanggiSet(self, 'Red', 'assets/red_pieces.png', 'assets/red_pieces.json') # mouse tracker self.mouseDown = False self.mouseReleased = False self.grabbed_piece = None self.moveList = [] # player turn self.turn = "Red" def run_game(self): self.initialize_pieces() while True: self.check_events() self.update_screen() self.clock.tick(self.game_settings.maxFPS) def check_events(self): cursor = pygame.mouse.get_pos() # cursor position for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: pygame.quit() sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: # mouse clicked if not self.grabbed_piece: # piece is clicked to pick up the piece. if self.turn == "Red": self.grabbed_piece = self.grab_piece( cursor, self.red_set) else: self.grabbed_piece = self.grab_piece( cursor, self.green_set) if self.grabbed_piece: self.fillAvailableMoves() elif self.grabbed_piece: # piece is currently grabbed and mouse is pressed to put the piece down. placed = self.placePiece(cursor) self.moveList = [] self.grabbed_piece = None if placed: if self.turn == "Red": self.turn = "Green" else: self.turn = "Red" def update_screen(self): self.screen = self.board.drawBoard() for piece in self.green_set.pieces: piece.draw(piece.boardPos) for piece in self.red_set.pieces: piece.draw(piece.boardPos) if self.grabbed_piece: for x, y in self.moveList: if self.board.boardGrid[x][ y] != 0 and self.turn not in self.board.boardGrid[x][ y].name: pygame.draw.circle(self.screen, (255, 0, 0), self.board.locCoord[x][y], 7) else: pygame.draw.circle(self.screen, (0, 255, 0), self.board.locCoord[x][y], 7) cursor = pygame.mouse.get_pos() self.grabbed_piece.boardPos = [cursor[0], cursor[1]] pygame.display.update() def placePiece(self, cursor): # place piece. Returns true if placed, else return false. if not cursor: print("Error in calcDistance. Cursor information not available.") gridX, gridY = None, None minDist = float('inf') tolerance = min(self.board_settings.xMargin, self.board_settings.yMargin) // 2 for x, y in self.moveList: coordX, coordY = self.board.locCoord[x][y][0], self.board.locCoord[ x][y][1] dist = math.sqrt((coordX - cursor[0])**2 + (coordY - cursor[1])**2) if dist < tolerance and dist < minDist: minDist = dist gridX, gridY = x, y print(self.green_set) print(self.red_set) if gridX is not None and gridY is not None: if self.board.boardGrid[gridX][gridY] != 0: if self.turn == "Green": self.red_set.remove_piece( self.board.boardGrid[gridX][gridY]) else: self.green_set.remove_piece( self.board.boardGrid[gridX][gridY]) self.board.boardGrid[gridX][gridY] = self.grabbed_piece self.board.boardGrid[self.grabbed_piece.gridPos[0]][ self.grabbed_piece.gridPos[1]] = 0 self.grabbed_piece.boardPos = self.board.locCoord[gridX][gridY] self.grabbed_piece.gridPos = [gridX, gridY] print(self.green_set) print(self.red_set) return True else: self.grabbed_piece.boardPos = self.board.locCoord[ self.grabbed_piece.gridPos[0]][self.grabbed_piece.gridPos[1]] return False def grab_piece(self, cursorPos, janggiSet): for piece in janggiSet.pieces: if piece.rect.collidepoint(cursorPos): print("{} is grabbed.".format(piece.name)) piece.grabbed = True return piece return def fillAvailableMoves(self): # returns all grid positions in which the piece is able to move. # TODO: If other team's piece is in the way, some pieces seems to have rules that disallows movement. # From my understandning of the rule, Ma and Sang cannot move in the direction if a piece is blocking the way. if not self.grabbed_piece: return [] curPos = self.grabbed_piece.gridPos boardLenX = len(self.board.boardGrid) boardLenY = len(self.board.boardGrid[0]) if "Zol" in self.grabbed_piece.name: directions = () if self.turn == "Red": directions = ((0, -1), (0, 1), (-1, 0)) elif self.turn == "Green": directions = ((0, -1), (0, 1), (1, 0)) for x, y in directions: posX, posY = curPos[0] + x, curPos[1] + y if 0 <= posX < boardLenX and 0 <= posY < boardLenY: if self.board.boardGrid[posX][posY] == 0: self.moveList.append([posX, posY]) else: if self.turn not in self.board.boardGrid[posX][ posY].name: self.moveList.append([posX, posY]) elif "Cha" in self.grabbed_piece.name: directions = ((1, 0), (0, 1), (-1, 0), (0, -1)) for x, y in directions: posX, posY = curPos[0] + x, curPos[1] + y while 0 <= posX < boardLenX and 0 <= posY < boardLenY and \ self.board.boardGrid[posX][posY] == 0: self.moveList.append([posX, posY]) posX += x posY += y if 0 <= posX < boardLenX and 0 <= posY < boardLenY and self.turn not in self.board.boardGrid[ posX][posY].name: self.moveList.append([posX, posY]) elif "Ma" in self.grabbed_piece.name: directions = ((2, 1), (2, -1), (1, 2), (-1, 2), (1, -2), (-1, -2), (-2, 1), (-2, -1)) for x, y in directions: posX, posY = curPos[0] + x, curPos[1] + y if 0 <= posX < boardLenX and 0 <= posY < boardLenY: if self.board.boardGrid[posX][posY] == 0: self.moveList.append([posX, posY]) else: if self.turn not in self.board.boardGrid[posX][ posY].name: self.moveList.append([posX, posY]) elif "Sang" in self.grabbed_piece.name: directions = ((3, 2), (3, -2), (-3, 2), (-3, -2), (-2, 3), (2, 3), (-2, -3), (2, -3)) for x, y in directions: posX, posY = curPos[0] + x, curPos[1] + y if 0 <= posX < boardLenX and 0 <= posY < boardLenY: if self.board.boardGrid[posX][posY] == 0: self.moveList.append([posX, posY]) else: if self.turn not in self.board.boardGrid[posX][ posY].name: self.moveList.append([posX, posY]) elif "Po" in self.grabbed_piece.name: # Po moves by jumping over other team's piece. Po cannot jump other team's Po. # When Po jumps, it can land on other team's piece and kill that piece. directions = ((1, 0), (-1, 0), (0, 1), (0, -1)) for x, y in directions: posX, posY = curPos[0] + x, curPos[1] + y while 0 <= posX < boardLenX and 0 <= posY < boardLenY and self.board.boardGrid[ posX][posY] == 0: posX, posY = posX + x, posY + y if 0 <= posX < boardLenX and 0 <= posY < boardLenY and "Po" in self.board.boardGrid[ posX][posY].name: continue else: posX, posY = posX + x, posY + y while 0 <= posX < boardLenX and 0 <= posY < boardLenY: if self.board.boardGrid[posX][ posY] != 0 and "Po" in self.board.boardGrid[ posX][posY].name: break self.moveList.append([posX, posY]) posX, posY = posX + x, posY + y elif "Sa" in self.grabbed_piece.name or "King" in self.grabbed_piece.name: # Sa can only move within the square where king resides. lowX, highX, lowY, highY = 0, 0, 0, 0 diagPos = [] straightPos = [] if self.turn == "Green": lowX, highX = 0, 2 lowY, highY = 3, 5 diagPos = [(0, 3), (0, 5), (2, 3), (2, 5), (1, 4)] straightPos = [(1, 3), (0, 4), (1, 5), (2, 4)] elif self.turn == "Red": lowX, highX = 7, 9 lowY, highY = 3, 5 diagPos = [(7, 3), (7, 5), (9, 3), (9, 5), (8, 4)] straightPos = [(8, 3), (8, 5), (7, 4), (9, 4)] directions = None if (curPos[0], curPos[1]) in diagPos: directions = ((-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)) else: directions = ((1, 0), (-1, 0), (0, 1), (0, -1)) for x, y in directions: posX, posY = curPos[0] + x, curPos[1] + y if lowX <= posX <= highX and lowY <= posY <= highY: if self.board.boardGrid[posX][posY] == 0: self.moveList.append([posX, posY]) else: if self.turn not in self.board.boardGrid[posX][ posY].name: self.moveList.append([posX, posY]) def check_checkMate(self): # if checkmate, return True pass def check_check(self): # if check, next user must make sure the king is not checked. pass def initialize_pieces(self): zolPos = 0 chaPos = 0 poPos = 1 maPos = 1 sangPos = 2 saPos = 3 for gPiece, rPiece in zip(self.green_set.pieces, self.red_set.pieces): if 'GreenZol' in gPiece.name and 'RedZol' in rPiece.name: self.board.boardGrid[3][zolPos] = gPiece self.board.boardGrid[6][zolPos] = rPiece gPiece.boardPos = self.board.locCoord[3][zolPos] rPiece.boardPos = self.board.locCoord[6][zolPos] gPiece.gridPos = [3, zolPos] rPiece.gridPos = [6, zolPos] zolPos += 2 elif 'GreenCha' in gPiece.name and 'RedCha' in rPiece.name: self.board.boardGrid[0][chaPos] = gPiece self.board.boardGrid[9][chaPos] = rPiece gPiece.boardPos = self.board.locCoord[0][chaPos] rPiece.boardPos = self.board.locCoord[9][chaPos] gPiece.gridPos = [0, chaPos] rPiece.gridPos = [9, chaPos] chaPos = 8 elif 'GreenPo' in gPiece.name and 'RedPo' in rPiece.name: self.board.boardGrid[2][poPos] = gPiece self.board.boardGrid[7][poPos] = rPiece gPiece.boardPos = self.board.locCoord[2][poPos] rPiece.boardPos = self.board.locCoord[7][poPos] gPiece.gridPos = [2, poPos] rPiece.gridPos = [7, poPos] poPos = 7 elif 'GreenMa' in gPiece.name and 'RedMa' in rPiece.name: self.board.boardGrid[0][maPos] = gPiece self.board.boardGrid[9][maPos] = rPiece gPiece.boardPos = self.board.locCoord[0][maPos] rPiece.boardPos = self.board.locCoord[9][maPos] gPiece.gridPos = [0, maPos] rPiece.gridPos = [9, maPos] maPos = 7 elif 'GreenSang' in gPiece.name and 'RedSang' in rPiece.name: self.board.boardGrid[0][sangPos] = gPiece self.board.boardGrid[9][sangPos] = rPiece gPiece.boardPos = self.board.locCoord[0][sangPos] rPiece.boardPos = self.board.locCoord[9][sangPos] gPiece.gridPos = [0, sangPos] rPiece.gridPos = [9, sangPos] sangPos = 6 elif 'GreenSa' in gPiece.name and 'RedSa' in rPiece.name: self.board.boardGrid[0][saPos] = gPiece self.board.boardGrid[9][saPos] = rPiece gPiece.boardPos = self.board.locCoord[0][saPos] rPiece.boardPos = self.board.locCoord[9][saPos] gPiece.gridPos = [0, saPos] rPiece.gridPos = [9, saPos] saPos = 5 elif 'GreenKing' in gPiece.name and 'RedKing' in rPiece.name: self.board.boardGrid[1][4] = gPiece self.board.boardGrid[8][4] = rPiece gPiece.boardPos = self.board.locCoord[1][4] rPiece.boardPos = self.board.locCoord[8][4] gPiece.gridPos = [1, 4] rPiece.gridPos = [8, 4] else: print("Initialize board failed. Check your pieces.") pygame.quit() sys.exit()