def __init__(this,wid=None,hei=None,mines=None,difficulty=None): this.grid = [] this.foundMine = False # used to alert game when you lose, hope to never have to use it... this.numRevealed = 0 # you win when numRevealed = w * h - totalMines this.mines = [] this.startedGame = False if (wid and hei and mines): this.h = hei this.w = wid this.numMines = mines this.totalMines = mines elif not difficulty is None: if difficulty is 0: this.h = 9 this.w = 9 this.numMines = 10 elif difficulty is 1: this.h = 16 this.w = 16 this.numMines = 40 elif difficulty is 2: this.h = 30 this.w = 16 this.numMines = 99 this.totalMines = this.numMines for y in range(this.w): this.grid.append([]) for x in range(this.h): tempSq = Square(0,vis=False) tempSq.setPosition(x,y) this.grid[y].append(tempSq)
def start(): inputString = """Press "'s' for Square "'rt' for Rectangle "'rh' for Rhombus "'p' for Parellelogram "'t' for Trapezoid "'qq' to Quit "- """ userInput = str(input(inputString)) while userInput != 'qq': if userInput == 's': Square.start(board, turtle) elif userInput == 'rt': Rectangle.start(board, turtle) elif userInput == 'rh': Rhombus.start(board, turtle) elif userInput == 'p': Parallelogram.start(board, turtle) elif userInput == 't': Trapezoid.start(board, turtle) else: pass userInput = str(input(inputString))
def _update_board(self, x, y): """ Expose squares after one move. """ # expose given square self._expose_square(x, y) # create a list of exposed squares squares = [Square(x, y, self.neighboring_mine_counts[x][y])] # if the square has a mine as a neighour we end up the update if self.neighboring_mine_counts[x][y] != 0: return squares # if have an explosion we end the update if self.mines_positions[x][y]: self._explosion = True return squares # exposing algorithm # push initial square in the stack, like dfs stack = [(x, y)] while len(stack) > 0: (x, y) = stack.pop() # remove top of the stack for dx, dy in itertools.product([-1, 0, 1], [-1, 0, 1]): if dx == 0 and dy == 0: # same as x and y continue next_x = x + dx next_y = y + dy if self._is_inside_the_board(next_x, next_y): # valid position if not self.exposed_squares[next_x][ next_y]: # not previously exposed self._expose_square(next_x, next_y) # expose the new square squares.append( Square( next_x, next_y, self.neighboring_mine_counts[next_x][next_y]) ) # add it on the exposed squares list if self._test_if_neighbor_count_is_0( next_x, next_y ): # we add it on the stack only if it has no mine neighbours stack.append((next_x, next_y)) # Returns a list of squares that have been exposed return squares
def emptyspace(self, inexterior="ExteriorSpace"): extsq = [] for i in range(self.height): for j in range(self.width): sq = self.getSquare(j, i) if sq.getTerrain().name == inexterior: if inexterior == "ExteriorSpace" and sq.hasequipment(): sq.takeequipment() extsq.append(sq) return(extsq)
def addMines(this,x,y): #parameters signify spot that was clicked, don't add mines around it minesToPlace = this.numMines while(minesToPlace>0): randY = random.randint(0,this.h-1) randX = random.randint(0,this.w-1) if this.grid[randX][randY].number != -1 and not (randY in range(y-1,y+2) and randX in range(x-1,x+2)): tempMine = Square(-1) tempMine.setPosition(randX,randY) this.mines.append(tempMine) this.grid[randX][randY] = tempMine minesToPlace-=1
def __init__(self): self.square = Square(SQUARE_X, SQUARE_Y, SQUARE_HEIGHT, SQUARE_WIDTH, [0, 0], SQUARE_SPEED) self.missiles = [] self.display = Display(SCREEN_WIDTH, SCREEN_HEIGHT) self.done_game = True self.done_all = False self.time_between_missiles = TIME_BETWEEN_MISSILES self.time_last_missile = 0 self.score = 0 self.client = Client()
def clean_board(): # Initialize values in the board new_grid = [[0 for j in range(0, 9)] for i in range(0, 9)] for sq_x in range(0, 9): # 0, 1, 2, 3, ...,8 for sq_y in range(0, 9): if grid[sq_y][sq_x] != 0: new_grid[sq_y][sq_x] = sq.Square(sq_x, sq_y, grid[sq_y][sq_x], False) else: new_grid[sq_y][sq_x] = sq.Square(sq_x, sq_y, 0, True) return new_grid
def extendRowRight(inputList): input = inputList[0] square = parseSquare(input) if len(inputList[1::]) > 0: square.nextSquare = extendRowRight(inputList[1::]) return square else: endSquare = Square() endSquare.tile = '$' square.nextSquare = endSquare return square
def drawMap(self): y = self.y for i in range(self.size): row = [] x = self.x for j in range(self.size): square = Square(self.canvas, x, y) row.append(square) x += 2 * square.getSize() + self.padding y += 2 * square.getSize() + self.padding self.map.append(row) self.map[self.start.x][self.start.y].setState(Type.Start) self.map[self.goal.x][self.goal.y].setState(Type.Goal)
def __init__(this,wid=9,hei=9,mines=10): this.grid = [] this.numMines = mines this.mines = [] this.startedGame = False this.h = hei this.w = wid for y in range(wid): this.grid.append([]) for x in range(hei): tempSq = Square(0,vis=False) tempSq.setPosition(x,y) this.grid[y].append(tempSq)
def main(argv): radius = '' side = '' age = '' material = '' try: opts, args = getopt.getopt(argv, "hr:s:a:m:", ["radius=", "side=", "age=", "material="]) except getopt.GetoptError: print("Error") usage() sys.exit(2) for opt, arg in opts: if opt == '-h': usage() sys.exit() elif opt in ("-r", "--radius"): radius = int(arg) elif opt in ("-s", "--side"): side = int(arg) elif opt in ("-a", "--age"): age = int(arg) elif opt in ("-m", "--material"): material = str(arg) square = Square(side) metal = Metal(material) ancientObject = AncientObject(age, metal) myCoin = ClassicalChinaCoin(radius, square, ancientObject) print(myCoin.toString()) if myCoin.isValid(): print("\nCoin is Valid") else: print("\nCoin is Invalid") square.setSide(2) metal.setMaterial("gold") ancientObject.setAge(700) ancientObject.setMetal(metal) myCoin.setRadius(5) myCoin.setSquare(square) myCoin.setAncientObject(ancientObject) print("\n" + myCoin.toString()) ancientObject.destroy() print("\nCoin Destroyed\n\n" + myCoin.toString())
def main(argv): radius = '' side = '' material = '' try: opts, args = getopt.getopt(argv,"hr:s:m:",["radius=", "side=", "material="]) except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt == '-h': usage() sys.exit() elif opt in ("-r", "--radius"): radius = arg elif opt in ("-s", "--side"): side = arg elif opt in ("-m", "--material"): material = arg square = Square.Square(int(side)) coin = SpecialChinaCoin.SpecialChinaCoin(material, float(radius), square) print (coin.toString()) print("-----------") coin.changeMaterial("gold"); print (coin.toString()) print("-----------") coin.enlarge(3) print (coin.toString()) print("-----------")
def hypermutants(self, wave): import HyperRadioactiveMutant if wave == 3: glomin = 10 else: glomin = 7 for mutidx in range(len(self.__mutants)): # Don't convert them more than once. if not isinstance(self.__mutants[mutidx], HyperRadioactiveMutant.HyperRadioactiveMutant): hypmutie = HyperRadioactiveMutant.HyperRadioactiveMutant(self.__mutants[mutidx], glomin) sq = self.__mutants[mutidx].square sq.removePiece() hypmutie.setPosition(sq) self.__mutants[mutidx] = hypmutie
def initEmptyBoard(self): board = [FirstSquare(0)] for player in self.players: board[0].enter(player) for i in range(1, self._size): board.append(Square(i)) return board
def button_pres(self): """ operating when the user clicked on the create button to create a shape or to change it if values are incorrect show msg in the screen """ x = self.x_start.get() y = self.y_start.get() side = self.side.get() color = self.color.get() line = self.line.get() if x.isdigit() and y.isdigit() and side.isdigit( ) and color is not "" and color in COLORS and line in COLORS and int( x) < 1001 and int(y) < 916: if self.shape is not None: self.canv.delete(self.shape) self.data.delete_value(self.shape) obj = [ Square(int(x), int(y), int(side), color, line), [int(x), int(y), int(side), color, line] ] obj_val = obj[0].draw_me(self.canv) self.data.set_value(obj_val, obj) destroy_Creat_Square() else: self.txt_Square.configure(text="invalid values")
def init_squares(self): # Init the squares for i in range(8): self.board.append([]) for j in range(8): cell = Square(i, j) self.board[i].append(cell)
def main(args): # Get options options = OPTIONS.copy() # Set debug level set_log_active(options["debug"]) print 'Solving %s for the %s problem.' % (solver_name, problem_name) # Create problem and solver problem = Square.Problem(options) solver = Heat.Solver(options) # Solve problem with solver wct = time() w = solver.solve(problem) # Compute elapsed time wct = time() - wct sys.stdout.flush() sys.stdout.write('\033[K') print 'Solved %s for the %s problem in %g seconds.' % (solver_name, problem_name, wct) return 0
def fill_empty_spaces(self, field_info): l.debug("Filling empty spaces with zeroes...") # Fill any empty spots with the previously extracted coordinates such that # the result is the complete game field. for row_index in range(0, len(self._initial_squares)): for column_index in range(0, len(self._initial_squares[row_index])): stored = self._initial_squares[row_index][column_index] checked_stored = Square(stored.center_coordinates, 0, False) # Empty fields at the ends must be added manually. if column_index >= len(field_info[row_index]): field_info[row_index].append(checked_stored) else: new = field_info[row_index][column_index] difference_x = abs(new.center_coordinates[0] - stored.center_coordinates[0]) # Distance greater than the previously calculated distance means # that an entry is missing here. if difference_x >= self._initial_square_width: field_info[row_index].insert(column_index, checked_stored) # Crude display of the result. l.debug("Filling results: {} rows with {} columns".format(len(field_info), list(map(lambda x: len(x), field_info)))) for row in field_info: line = "" for column in row: if column.is_unchecked: line += "?" else: line += str(column.value) l.debug(line)
def residentmutants(self): muties = [] for i in range(self.height): for j in range(self.width): sq = self.getSquare(j, i) if sq.isOccupied() and sq.piece.name == "Mutant": muties.append(sq.piece) return(muties)
def __init__(self, window): self.window = window ''' The game board is made up of 4 rows and 4 columns - 16 squares, with 15 labelled images (1 to 15) and a blank square image. However, because Python lists and tuples start at zero, the squares are internally numbered (indexed) 0 to 15, like this: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 (A Square is an area of the window, each contains a tile, which is movable.) The following is a dict of squareNumber:tuple. Each tuple contains all moves (vertical and horizontal neighbors) that can switch with this square. For example, for Square 0, only Squares 1 and 4 are legal moves. ''' LEGAL_MOVES_DICT = { 0: (1, 4), 1: (0, 2, 5), 2: (1, 3, 6), 3: (2, 7), 4: (0, 5, 8), 5: (1, 4, 6, 9), 6: (2, 5, 7, 10), 7: (3, 6, 11), 8: (4, 9, 12), 9: (5, 8, 10, 13), 10: (6, 9, 11, 14), 11: (7, 10, 15), 12: (8, 13), 13: (9, 12, 14), 14: (10, 13, 15), 15: (11, 14) } yPos = Game.START_TOP self.squaresList = [] # Create list of Square objects for row in range(0, 4): xPos = Game.START_LEFT for col in range(0, 4): squareNumber = (row * 4) + col legalMovesTuple = LEGAL_MOVES_DICT[squareNumber] oSquare = Square(self.window, xPos, yPos, squareNumber, legalMovesTuple) self.squaresList.append(oSquare) xPos = xPos + SQUARE_WIDTH yPos = yPos + SQUARE_HEIGHT self.soundTick = pygame.mixer.Sound('sounds/tick.wav') self.soundApplause = pygame.mixer.Sound('sounds/applause.wav') self.soundNope = pygame.mixer.Sound('sounds/nope.wav') self.playing = False self.startNewGame()
def create_grid(self): """ Creates the whole grid :return: None """ for i in range(4): for j in range(4): square = Square(i, j) self.grid.append(square)
def draw_board(self): '''draws the board on the canvas''' self._canvas.delete(tkinter.ALL) self.square_list = [] #updates the game information window self._white_score.set(self.gamestate._white_score) self._black_score.set(self.gamestate._black_score) self._current_color.set(self.gamestate.current_color) for y in range(self.gamestate.board_rows): for x in range(self.gamestate.board_columns): #Find fractional coordinates for drawing one square/circle min_x = x / self.gamestate.board_columns min_y = y / self.gamestate.board_rows max_x = (x + 1) / self.gamestate.board_columns max_y = (y + 1) / self.gamestate.board_rows #create coordinate objects tlc = coordinate.from_frac(min_x, min_y) brc = coordinate.from_frac(max_x, max_y) #find current canvas dimensions width = self._canvas.winfo_width() height = self._canvas.winfo_height() #find the absolute coordinates given current canvas dimensions #and coordinate objects of top-left corner and bottom-right corner tlc_x, tlc_y = tlc.absolute(width, height) brc_x, brc_y = brc.absolute(width, height) #determines the color of the circle color = '#68daae' if self.gamestate.board[y][x] == 'black': color = 'black' elif self.gamestate.board[y][x] == 'white': color = 'white' #creates a Square object to register click positions #creates an oval and rectangle to draw the piece and lines, respectively self.square_list.append( Square.Square(tlc, brc, width, height, x, y)) self._canvas.create_rectangle(tlc_x, tlc_y, brc_x, brc_y, fill='#ff6b62') self._canvas.create_oval(tlc_x, tlc_y, brc_x, brc_y, fill=color) #after drawing the board, checks if the game is over if self.gamestate.game_over(): self._winner.set(self.gamestate.find_winner())
def __init__(self): self.__playboard = list() self.__stack = list() self.King = {Color.BLACK: None, Color.WHITE: None} for i in range(8): self.__playboard.append([]) for j in range(8): self.__playboard[i].append(Square((i, j))) self.readyToPlay() self.__stack.append(self.playboard)
def clear(self): for i in range(0, 8): for j in range(8, 0, -1): if j == 8: self.squares[(Board.letters[i], j)] = Square.Square(Board.startingPieces[i], "black") elif j == 1: self.squares[(Board.letters[i], j)] = Square.Square(Board.startingPieces[i], "white") elif j == 7: self.squares[(Board.letters[i], j)] = Square.Square("Pawn", "black") elif j == 2: self.squares[(Board.letters[i], j)] = Square.Square("Pawn", "white") else: self.squares[(Board.letters[i], j)] = Square.Square("0")
def update_square_index(self): for i in range(0, self.height): if i > 0: self.index -= 8 for j in range(0, self.width): # Initialization: Aim to make 12 independent squares temp = sq.Square() self.matrix[i][j] = temp self.matrix[i][j].pos_update(self.index) self.index += 1
def main(argv): radius = '' side = '' age = '' material = '' try: opts, args = getopt.getopt(argv,"hr:s:a:m:",["radius=", "side=", "age=", "material="]) except getopt.GetoptError: usage() for opt, arg in opts: if opt == '-h': usage() sys.exit() elif opt in ("-r", "--radius"): radius = arg elif opt in ("-s", "--side"): side = arg elif opt in ("-a", "--age"): age = arg elif opt in ("-m", "--material"): material = arg print("***** My Coin by default *****") square = Square.Square(1) metal = Metal.Metal('cupper') myCoin = ClassicalChinaCoin.ClassicalChinaCoin(3, square, 600, metal) print (myCoin.toString()) if myCoin.isValid(): print("My coin is valid.") else: print("My coin is invalid.") print("------------------") print("***** Change my coin *****") myCoin.setRadius(radius) myCoin.getSquare().setSide(side) myCoin.setAge(age) myCoin.getMetal().changeMaterial(material); print (myCoin.toString()) if myCoin.isValid(): print("My coin is valid.") else: print("My coin is invalid.") print("-----------") print("***** Destroy my coin *****") myCoin.destroy() print (myCoin.toString()) if myCoin.isValid(): print("My coin is valid.") else: print("My coin is invalid.") print("-----------")
def add_next_square_char(self, current_row): next_square_char = self.my_file.read(1) if (next_square_char == "\n"): #if we've reached the end of the line, end the loop return False else: #if we haven't reached the end of the line, add this Square to the row new_square_object = Square(next_square_char) current_row.append(new_square_object) return True
def createGrid(self, file_name): types = [ 0, NORMAL_GRD_COST, MODERATE_GRD_COST, HARD_GRD_COST, LOCKED_GRD_COST ] data = open(r'data/' + file_name + '.txt') data = [line.split(',') for line in data.readlines()] for row in range(GRD_LENGTH): elements = [] for column in range(GRD_LENGTH): value = int(data[row][column]) elements.append(Square(value, types[value])) self.grid.append(elements)
def parseSquare(input): square = Square() if input == 'DW': square.wordBonus = 2 elif input == 'TW': square.wordBonus = 3 elif input == 'DL': square.letterBonus = 2 elif input == 'TL': square.letterBonus = 3 else: square.tile = input return square
def __init__(self, x_pos, y_pos): # use a list to store all components of a grid self.x_pos = x_pos self.y_pos = y_pos self.square_lst = [] self.ship_lst = [] self.hit_lst = [] # create squares for row in range(1,11): for col in "ABCDEFGHIJ": sq = Square.Square(x_pos, y_pos, (col, row)) # create a new Square object self.square_lst.append(sq) # append it to the list of squares x_pos += Constants.LENGTH; # set the x-coor of the next square x_pos = self.square_lst[0].x_pos # prepare for the next row y_pos += Constants.LENGTH
def main(): ''' For these lines, rearrange the arguments so that they are in the same order as the ones you passed in your __init__ functions. ''' circle = Circle(3, True, "red") if circle.getFilled() == True: print("The", circle.getColor(), " circle has an area of", circle.area(), ", and a circumference of", circle.circumference()) elif circle.getFilled() == False: print("The circle has an area of", circle.area(), ", a circumference of", circle.circumference()) square = Square(5, False, "maroon") if square.getFilled() == True: print("The", square.getColor(), " square has an area of", square.area(), ", and a perimeter of", square.perimeter()) elif square.getFilled() == False: print("The square has an area of", square.area(), ", a perimeter of", square.perimeter())
def __init__(self, default=True, id=-1): self.cube = [ Square.Square(1), Square.Square(2), Square.Square(3), Square.Square(4), Square.Square(5), Square.Square(6) ] self.queueReady = False self.sides = 6 self.id = id
def initBoard(self): i = 0 for n in range(self.BoardHeight): ii = 0 for m in range(self.BoardWidth): square = Square.Square(self, n, m) self.squares[str(square.m)+","+str(square.n)] = square square.setGeometry(ii, i, 40, 40) if ((m == 7 and n == 7) or (m == 4 and n == 4) or (m == 4 and n == 10) or (m == 10 and n == 4) or (m == 10 and n == 10)): square.setNormal2() else: square.setNormal() self.connect(square, QtCore.SIGNAL('clicked()'), self.play) ii = ii + 40 i = i + 40 print(self.board)
def __init__(self): super(Board, self).__init__() self.__tab = [] # List containing the squares of the board color = "black" # first color for A1 # Computation of the color for each square of the board for i in range(8): if "white" in color: color = "black" else: color = "white" for j in range(8): if "white" in color: color = "black" else: color = "white" self.__tab.append(Square(color))
def readMove(self): ok = 0 while ok == 0: row = input("Give row(1-8)").strip() '''if row>='1' and row<='8': row=int(row)-1 ok=1 else: print("wrong row input")''' if row.isdigit(): row = int(row) if row >= 1 and row <= 8: row = row - 1 ok = 1 else: print("wrong row input") OK = 0 while OK == 0: col = input("Give col(a-h)").lower().strip() if col >= 'a' and col <= 'h': OK = 1 if col == 'a': col = 0 elif col == 'b': col = 1 elif col == 'c': col = 2 elif col == 'd': col = 3 elif col == 'e': col = 4 elif col == 'f': col = 5 elif col == 'g': col = 6 elif col == 'h': col = 7 else: print("wrong col input") return Square(row, col)
def __init__(self): self.agent = ag.Agent() self.index = 9 self.width = 4 self.height = 3 # To create a map with 4*3 size self.matrix = np.array([[sq.Square()] * self.width] * self.height) self.squares = { 1: self.matrix[2][0], 2: self.matrix[2][1], 3: self.matrix[2][2], 4: self.matrix[2][3], 5: self.matrix[1][0], 6: self.matrix[1][1], 7: self.matrix[1][2], 8: self.matrix[1][3], 9: self.matrix[0][0], 10: self.matrix[0][1], 11: self.matrix[0][2], 12: self.matrix[0][3] }
def clearmutants(self): for i in range(self.height): for j in range(self.width): sq = self.getSquare(j, i) if sq.isOccupied() and sq.piece.name == "Mutant": sq.removePiece()