def main(self): """main function""" board = Board(15, 15, 32) board.read_map('resources/structure.txt') board.set_components() mac = Actor(board.start) gui = Gui(board.width, board.height) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if mac.status == 'alive': if event.key == pygame.K_UP: mac.move(0, -32, board) elif event.key == pygame.K_LEFT: mac.move(-32, 0, board) elif event.key == pygame.K_DOWN: mac.move(0, +32, board) elif event.key == pygame.K_RIGHT: mac.move(+32, 0, board) else: if event.key == pygame.K_RETURN: return self.main() elif event.key == pygame.K_ESCAPE: pygame.quit() sys.exit() gui.draw(mac, board) pygame.display.update()
class Game: world = 0 camera = 0 background = 0 gui = 0 mainbody = 0 gameResult = 0 currentLevel = 1 def __init__(self): self.world = World() self.camera = Camera() def setupMenu(self): self.gui = Gui() self.gui.setupMenu(self) self.setupBackground('levels/menu.xml') def setupLevel(self, *largs): print "CURRENT LEVEL %d"%self.currentLevel levelstring = 'levels/level' levelstring +=`self.currentLevel`.zfill(2) levelstring +='.xml' print levelstring if os.path.isfile(levelstring): self.camera.scale = 1.1 self.gui.messaging.reset() self.gameResult = 0 self.setupWorld(levelstring) self.setupBackground(levelstring) self.setupShip(levelstring) self.gui.messaging.displayText('Level %d'%(self.currentLevel),60) else: self.gui.messaging.reset() self.mainbody = 0 self.setupWorld('levels/endgame.xml') self.setupBackground('levels/endgame.xml') self.gui.messaging.displayText('Congratulations ! !',-1) def checkVictoryCondition(self): if self.mainbody.isStable() == 0: return 0 landingzone = self.world.getLandingzone() if landingzone.checkBody(self.mainbody) == 1: return 1 else : return -1 def gameIsRunning(self): if self.mainbody != 0 and self.gameResult == 0: return 1 def setupBackground(self,filename): self.background = Background() domLevel = parse(filename) backgroundNodes = domLevel.getElementsByTagName("background") backgroundNode = backgroundNodes[0] for node in backgroundNode.childNodes: if node.localName == "layer": texturename = 0 tilesizex = 0 tilesizey = 0 positionx = 0 positiony = 0 layersizex = 0 layersizey = 0 offsetx = 0 offsety = 0 for childnode in node.childNodes: if childnode.localName == "texture": texturename = childnode.getAttribute('value') if childnode.localName == "tilesize": values = childnode.getAttribute('value').split(',') if values[0] == 'screenw': tilesizex = Config.getint('graphics', 'width') else: tilesizex = float(values[0]) if values[1] == 'screenh': tilesizey = Config.getint('graphics', 'height') else: tilesizey = float(values[1]) if childnode.localName == "position": values = childnode.getAttribute('value').split(',') if values[0] == 'screenw': positionx = Config.getint('graphics', 'width') else: positionx = float(values[0]) if values[1] == 'screenh': positiony = Config.getint('graphics', 'height') else: positiony = float(values[1]) if childnode.localName == "offset": values = childnode.getAttribute('value').split(',') if values[0] == 'screenw': offsetx = Config.getint('graphics', 'width') else: offsetx = float(values[0]) if values[1] == 'screenh': offsety = Config.getint('graphics', 'height') else: offsety = float(values[1]) if childnode.localName == "layersize": values = childnode.getAttribute('value').split(',') if values[0] == 'screenw': layersizex = Config.getint('graphics', 'width') else: layersizex = float(values[0]) if values[1] == 'screenh': layersizey = Config.getint('graphics', 'height') else: layersizey = float(values[1]) layer = Layer(TextureHelper.loadTextureFromFile(texturename),tilesizex,tilesizey,positionx,positiony,offsetx,offsety,layersizex,layersizey) self.background.addLayer(layer) def setupShip(self,filename): domLevel = parse(filename) shipNodes = domLevel.getElementsByTagName("ship") shipNode = shipNodes[0] self.mainbody = Body() for node in shipNode.childNodes: if node.localName == "position": position = node.getAttribute('value') values = position.split(',') self.mainbody.setPosition(float(values[0]),float(values[1])) if node.localName == "mobile": m = Mobile() for childnode in node.childNodes: if childnode.localName == "position": values = childnode.getAttribute('value').split(',') m.setPosition(float(values[0]),float(values[1])) if childnode.localName == "velocity": values = childnode.getAttribute('value').split(',') m.setVelocity(float(values[0]),float(values[1])) if childnode.localName == "thrust": values = childnode.getAttribute('value').split(',') m.setThrustVector(float(values[0]),float(values[1])) m.setInitialThrustVector(float(values[0]),float(values[1])) if childnode.localName == "mass": value = childnode.getAttribute('value') m.setMass(float(value)) if childnode.localName == "radius": value = childnode.getAttribute('value') m.setRadius(float(value)) if childnode.localName == "texture": value = childnode.getAttribute('value') m.setTexture(TextureHelper.loadTextureFromFile(value)) #if childnode.localName == "physicalPoints": # for ppointnode in childnode.childNodes: # if ppointnode.localName == "point": # values = ppointnode.getAttribute('value').split(',') # m.addPhysicalPoint(Vector2d(float(values[0]),float(values[1]))) m.setupPhysicalPoint() self.mainbody.addMobile(m) self.mainbody.init() focus_position = self.mainbody.getPosition() self.world.addMobile(self.mainbody) def setupWorld(self,filename): self.world.reset() domLevel = parse(filename) worldNodes = domLevel.getElementsByTagName("world") for node in worldNodes[0].childNodes: if node.localName == "gravity": values = node.getAttribute('value').split(',') self.world.setGravity(float(values[0]),float(values[1])) if node.localName == "landingzone": values = node.getAttribute('value').split(',') self.world.setLandingzone(Landingzone(float(values[0]),float(values[1]),float(values[2]),float(values[3]),TextureHelper.loadTextureFromFile('checker.png'))) h = Config.getint('graphics', 'height') w = Config.getint('graphics', 'width') p0 = Plane(1,0,-10) p1 = Plane(0,-1,h-10) p2 = Plane(-1,0,w-10) p3 = Plane(0,1,-64) self.world.addPlane(p0) self.world.addPlane(p1) self.world.addPlane(p2) self.world.addPlane(p3) #self.world.setGravity(0.0,-1.8) def setupGame(self): self.setupMenu() def updateGame(self,canvas): if self.mainbody != 0: self.camera.follow(self.mainbody) self.camera.setup(canvas) self.background.draw(canvas) self.world.draw(canvas) self.gui.draw(canvas) self.world.step(1/60.) if self.gameIsRunning(): res = self.checkVictoryCondition() if res != 0: if res == -1: self.gui.messaging.displayText('FAIL ! !',200) self.gameResult = -1 Clock.schedule_once(self.setupLevel, 5) if res == 1: self.gui.messaging.displayText('SUCCESS ! !',200) self.gameResult = 1 self.currentLevel += 1 Clock.schedule_once(self.setupLevel, 5) def on_touch_down(self, touch): worldpos = self.camera.screenToWorld(touch.pos[0],touch.pos[1]) self.world.on_touch_down(worldpos) self.gui.on_touch_down(touch)
class Oxo(): gui: Gui = None stop_game = False board = None player_ones_turn = True game_over = False board_size = Size(3, 3) def window_close(self): self.stop() def click_cell(self, x: int, y: int): if self.game_over: return if self.board[y][x] != Cell.EMPTY: return if self.player_ones_turn: self.board[y][x] = Cell.X else: self.board[y][x] = Cell.O if self.max_same_cell_row_count(x, y) >= 3: self.game_over = True spelernaam = "één" if self.player_ones_turn else "twee" self.gui.draw(self.board, f"Speler {spelernaam} is gewonnen!") else: self.player_ones_turn = not self.player_ones_turn spelernaam = "één" if self.player_ones_turn else "twee" self.gui.draw(self.board, f"Speler {spelernaam} is aan zet") def max_same_cell_row_count(self, cx: int, cy: int): counts = [] # Iterate top-left, -middle and -right for dx in range(-1, 2): dy = -1 counts.append(self.same_cell_row_count(cx, cy, dx, dy)) # Check left dx = -1 dy = 0 counts.append(self.same_cell_row_count(cx, cy, dx, dy)) return max(counts) def same_cell_row_count(self, cx: int, cy: int, dx: int, dy: int): """Returns the number of same-value cells in a row. Checks both the (dx, dy) direction and its oposite. """ return (self.directed_same_cell_row_count(cx, cy, dx, dy) + 1 + self.directed_same_cell_row_count(cx, cy, -dx, -dy)) def directed_same_cell_row_count(self, cx: int, cy: int, dx: int, dy: int): """Returns the number of same-value cells in a row. Checks the (dx, dy) direction (delta-x, -y). """ center_val = self.board[cy][cx] count = 0 x, y = (cx + dx, cy + dy) if not self.is_on_board(x, y): return count val = self.board[y][x] while val == center_val: count += 1 # Delta-extended-x, -y dex, dey = (dx * (count + 1), dy * (count + 1)) x, y = (cx + dex, cy + dey) if not self.is_on_board(x, y): break val = self.board[y][x] return count def is_on_board(self, x, y): return (x >= 0 and x < self.board_size.width and y >= 0 and y < self.board_size.height) def stop(self): print("\nExiting...") if self.gui is not None: self.gui.stop() self.stop_game = True def start(self): self.board = [[Cell.EMPTY for x in range(self.board_size.width)] for y in range(self.board_size.height)] size = 500, 500 self.gui = Gui(size, Color("blue"), Color("white"), GuiHandlers(self.click_cell, self.window_close)) self.gui.init() self.gui.draw(self.board, "Speler één is aan zet") while not self.stop_game: sleep(0.05)
def main(): pygame.init() screen = pygame.display.set_mode((640, 480),pygame.SWSURFACE) pygame.key.set_repeat(100, 100) '''TEST''' g=Gui() #g.enableDirtyRect() g.optimizeDraw() i=PygameInput() Image.mImageLoader=PygameImageLoader() gr=PygameGraphics() gr.setTarget(screen) f=ImageFont("C:\Python25\Projects\Guichan\consolefont.bmp") #f=ImageFont("consolefont.bmp") f.setColorkey( Color(255,0,255) ) f.setGlyphSpacing(2) f2=PygameFont("C:\Python25\Projects\Guichan\LiberationMono-Regular.ttf",14,Color(0,0,0,255)) #f2=PygameFont("C:\Python25\Projects\Guichan\Caracteres L1.ttf",13,Color(0,0,0,255)) f2.setGlyphSpacing(1) Widget.setGlobalFont(f2) c=Container() c.setOpaque(False) c.setPosition(0,0) c.setSize(640,480) c.setBaseColor( Color(255,0,0,255) ) a=ActionListener() a.action=action b, b2=Button("YEY!"), Button("WHa?") b.setPosition(0,50) b.setActionEventId("Button 1") b.addActionListener(a) b2.setPosition(100,100) b2.setActionEventId("Button 2") b2.addActionListener(a) b2.setBaseColor( Color(200,200,200) ) b2.setCaption("ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()") w,w2=Window("Hey over here!"), Window("Trapped in a window!") wColor=w.getBaseColor() wColor.a=200 w.setBaseColor(wColor) w.setTextColor(Color(255,0,255)) xyz=Button("XYZ") xyz.setTextColor(Color(0,255,255)) pb=ProgressBar(100.0) pb.setBaseColor( Color(255,255,0) ) pb.setForegroundColor( Color(0,255,255) ) pb.setSize(100, 20) pb.setPosition(300, 300) pb.setValue(50.0) c.add(w,0,100) c.add(b) c.add(b2) c.add(xyz,10,10) c.add(pb) check=Checkbox("Ye what? GET BACK HERE BOY!") check.setActionEventId("Checkbox") check.addActionListener(a) text=TextField("Hey Hey Hey Hey Hey Hey Hey Hey") text.setBackgroundColor( Color(255,255,255,255) ) text.setMaxSize(150) text2=TextBox("Hey, HeyTrapped in a window!\nWhat's goin' onTrapped in a window!\ntodays???Trapped in a window!") text2.setTabSize(10) sc=ScrollArea(text2) sc.setSize(200,100) rBox=Container() r1=RadioButton("1984","Dystopia") r2=RadioButton("Fahrenheit 451","Dystopia") r3=RadioButton("Brave New World","Dystopia") rBox.add(r1,0,0) rBox.add(r2,0,r1.getY()+r1.getHeight()) rBox.add(r3,0,r2.getY()+r2.getHeight()) label=Label("WE AIN'T GOT IT") ico_image=Image.load("C:\Python25\Projects\Guichan\May.bmp") ico=Icon(ico_image) lb=ListBox( List_ListModel(["Bollocks!","Never!","Cuppa tea, mate?","Hello!","Goodbye!","OK Computer!","Oh Inverted World!","How To Disappear Completely!","Hold Still!","It Takes A Train To Cry!","A","B","C","D","E","F","G","H","I",]) ) sc2=ScrollArea(lb) sc2.setSize(125,100) lb.setWidth(110) slider=Slider(0,100) slider.setOrientation(Slider.Orientation.VERTICAL) slider.setSize(15,100) slider.setActionEventId("Slider") #slider.addActionListener(a) ib=ImageButton(ico_image) ta=TabbedArea() c.add(w2) ta.addTab("Text",[ (text,0,0), (sc,0,50) ]) ta.addTab("Check",check) ta.addTab("Radio",rBox) ta.addTab("List",[ (sc2,0,0) ]) ta.addTab("Label",label) ta.addTab("Icon",[ (ico,0,0), (ib,100,0) ]) ta.addTab("Slider",slider) ta.setSize(300,300) w2.add(ta,0,0) g.setGraphics(gr) w2.resizeToContent() w.setSize(300,300) g.setInput(i) g.setTop(c) clock=pygame.time.Clock() g.mDirtyRect.addRect( Rectangle(0,0,640,480) ) done=False while done == False: clock.tick(0) for event in pygame.event.get(): if event.type==KEYDOWN: if event.key == K_ESCAPE: c.remove(b) c.remove(b2) done=True elif event.key == K_RETURN: w=Window("It'a window!") w.add(Checkbox("Kool thing")) w.resizeToContent() c.add(w, 10, 10) elif event.key == K_LEFT: pb.setValue( pb.getValue()-1.0 ) elif event.key == K_RIGHT: pb.setValue( pb.getValue()+1.0 ) if event.type == ACTIVEEVENT: if event.gain == 1: g.mDirtyRect.addRect( Rectangle(0,0,640,480) ) i.pushInput(event) g.logic() b2.setCaption( str( int(clock.get_fps()) ) ) fRect=GuichanToPygameDirtyRect(g.mDirtyRect.getList()) #for ix in fRect: screen.fill((255,0,0),ix) screen.fill((255,0,0)) g.draw() #pygame.display.update( GuichanToPygameDirtyRect(g.mDirtyRect.getList()) ) pygame.display.update() g.mDirtyRect.clearList()
class Kitchen(object): """ Kitchen environment for Kitchen for Progress 2D. Serves as main API interface. """ def __init__(self): # PyGame Initialization pygame.display.init() self.clock = pygame.time.Clock() self.gui = Gui() self.gripper = Gripper() self.plan = [] self.cur_plan = [] self.cur_action = '' self.target_name = None self.beput_name = None self.action_status = True #to check if the current action is done self.plan_status = True #to check if the plan is done #self.in_grip_obj = None #None if there is no object in the gripper # def pour(self, bepour, target): self.cur_plan.append('pouring') self.plan += ['pour', target, bepour] self.plan_status = False self.run() def fill_water(self, target, faucet): self.cur_plan.append('filling water') self.plan += [ 'pick', target, 'back', target, 'put', target, faucet, 'fill_water', 'none' ] self.plan_status = False self.run() def stir(self, target, bestir): self.cur_plan.append('stirring') self.plan += [ 'put', target, bestir, 'pick', target, 'stir', target, 'back', target ] self.plan_status = False self.run() def pick_up(self, target): """ Adds `pick up` operation to existing plan; Picks up `target`. Input: `target`, a string denoting target object """ self.cur_plan.append('picking up target') self.plan += ['pick', target, 'back', target] self.plan_status = False self.run() def put(self, target, beput): """ Adds `put` operation to existing plan; Puts `beput` onto `target`. Input: `target`, a string denoting target platform `beput`, string denoting object to be put """ self.cur_plan.append('putting target') self.plan += ['put', target, beput, 'back', 'none'] self.plan_status = False self.run() def open_drawer(self, target): self.cur_plan.append('opening drawer') self.plan += ['pick', target, 'open', target] self.plan_status = False self.run() def close_drawer(self, target): self.cur_plan.append('closing drawer') self.plan += ['pick', target, 'close', target] self.plan_status = False self.run() def _execute_plan(self): """ If the last action was completed, pop the next action from our plan. Execute the action. """ if self.action_status and len(self.plan): self.cur_action = self.plan.pop(0) self.target_name = self.plan.pop(0) if self.cur_action == 'put' or self.cur_action == 'pour': self.beput_name = self.plan.pop(0) self.action_status = self.gui.executeAction(self.gripper, self.cur_action, self.target_name, self.beput_name) #if the last action of the plan is done if self.action_status and len(self.plan) == 0: self.plan_status = True def run(self): """ Run the kitchen environment and display it. """ while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if self.plan_status == False: self._execute_plan() self.gui.draw(self.gripper, self.cur_action) pygame.display.flip() self.clock.tick(60) if self.plan_status: break
class Minesweeper(object): """ Main game application """ def __init__(self, difficulty, use_ai, total_games): # read settings file with open('settings.yaml', 'r') as f: settings = yaml.load(f) self.rows = settings[difficulty]["rows"] self.cols = settings[difficulty]["columns"] self.mines = settings[difficulty]["mines"] self.width = settings[difficulty]["width"] self.height = settings[difficulty]["height"] self.size = self.width, self.height # pygame setup self._running = True # used to stop game loop self.screen = self.setup_screen() # scorekeeping self.start_time = time.time() self.time_elapsed = 0 self.score = 0 self.lost_game = False self.won_game = False # game board setup # AI / autoplay self.use_ai = use_ai # create board and gui self.board = Board(self.width, self.height, self.rows, self.cols, self.mines, self.screen, 36) self.gui = Gui(self.board, self) # autoplay or enter event loop if self.use_ai: self.autoplay(total_games) self.loop() def autoplay(self, times_to_play): """ Automatically play minesweeper a certain number of times. :param times_to_play: int """ for i in range(times_to_play): print "\n### Playthrough", i # draw the starting board; also draws scores self.draw() # play 1 game solver.Solver.play_best_guess(self) # reset board self.reset_game() def game_over(self): # unflag and reveal all cells for i in xrange(self.rows): for j in xrange(self.cols): self.board.cells[i][j].revealed = True def reset_game(self): # reset score and draw new board self.lost_game = False self.won_game = False self.score = 0 self.start_time = time.time() self.time_elapsed = 0 self.board.reset() self.draw() def flag_cell(self, i, j): """ Flags cell and redraws board when user right-clicks or control-clicks cell :param i: cell row :param j: cell column """ # do not flag revealed squares if not self.board.cells[i][j].revealed: if self.board.cells[i][j].flagged == True: self.board.cells[i][j].flagged = False else: self.board.cells[i][j].flagged = True if self.test_did_win(): self.game_over() def reveal_cell(self, row, col): """ Mark a cell as revealed and if it's not a mine either display its neighbor count or reveal its empty neighbors. :param row: int, row index for cell to reveal in board :param col: int, col index for cell to reveal in board """ cell = self.board.cells[row][col] if cell.is_mine == True: print "You lose! Final Score: ", self.score cell.revealed = True cell.detonated = True self.lost_game = True self.game_over() elif cell.neighbors > 0: # cell has a neighbor # value, show it cell.revealed = True self.score += 1 else: # cell is empty, reveal all empty neighbors cell.revealed = True self.score += 1 self.reveal_neighbors(row, col) def reveal_neighbors(self, row, col): """ Recursive function that marks all adjacent unrevealed empty cells as revealed :param row: int, row index for cell in board :param col: int, col index for cell in board """ neighbors = self.board.get_neighbor_cells(row, col) for cell in neighbors: # if not revealed yet, reveal it and reveal its neighbors if not cell.revealed: cell.revealed = True if cell.neighbors == 0 and cell.is_mine == False: self.reveal_neighbors(cell.row, cell.col) """ # Pygame Setup and Event Functions """ def setup_screen(self): """ :return: pygame screen object """ pygame.init() screen = pygame.display.set_mode(self.size, pygame.HWSURFACE | pygame.DOUBLEBUF) screen.fill(colors.bg_gray) pygame.display.flip() return screen def loop(self): """ Game loop that responds to user events """ self._running = True while (self._running): # increment the game clock if we're playing now if (not self.lost_game) and (not self.won_game): now = time.time() self.time_elapsed = now - self.start_time # listen for user input events for event in pygame.event.get(): self.on_event(event) # draw the updated game board and score self.draw() def on_event(self, event): """ Handle individual events :param event: pygame event """ if event.type == pygame.QUIT: print "App quitting" self._running = False # keypresses elif event.type == KEYDOWN: if event.key == K_ESCAPE: self._running = False # mouse events elif event.type == MOUSEBUTTONUP: # left-click if event.button == 1: # macs don't have right click, so process control-click as right click key = pygame.key.get_pressed() if key[K_LCTRL]: self.flag_event(event) else: # left click reveals a cell x,y = event.pos if self.gui.button_icon.rect.collidepoint(x,y): self.reset_game() if self.gui.auto_icon.rect.collidepoint(x,y): self.autoplay(total_games) self.reset_game() else: for i in xrange(self.rows): for j in xrange(self.cols): cell_rect = self.board.cells[i][j].rect if cell_rect.collidepoint(x,y): # if unrevealed, reveal the cell if not self.board.cells[i][j].revealed: self.reveal_cell(i, j) # test if we won or not if self.test_did_win(): self.game_over() # right click elif event.button == 3: self.flag_event(event) def flag_event(self, event): """ Action taken when screen is right-clicked or ctrl-clicked :param event: :return: """ x,y = event.pos for i in xrange(self.rows): for j in xrange(self.cols): cell_rect = self.board.cells[i][j].rect if cell_rect.collidepoint(x,y): self.flag_cell(i, j) self.draw() def draw(self): # Fill background background = pygame.Surface(self.screen.get_size()) background = background.convert() background.fill(colors.gray) self.board.draw() self.gui.draw() # update scoreboard pygame.display.flip() # update screen def test_did_win(self): """ Tests whether the game's board is in a winning position. Also sets self.won_game for use in the solver. Winning conditions: All cells revealed or with flags All mines have flags No cells without mines have flags :return: bool """ did_win = True for i in xrange(self.rows): for j in xrange(self.cols): cell = self.board.cells[i][j] # unrevealed and not flagged squares if not cell.revealed and not cell.flagged: did_win = False break # incorrect flags if cell.flagged and not cell.is_mine: did_win = False break # unflagged mines if cell.is_mine and not cell.flagged: did_win = False break if did_win: print "You won!" self.won_game = True return did_win
class Oxo(): gui: Gui = None net: Net = None stop_game = False board = None is_my_turn = False im_player_one = None game_over = False board_size = Size(3, 3) def game_start(self, im_player_one: bool): self.im_player_one = im_player_one self.is_my_turn = self.im_player_one if self.is_my_turn: self.gui.draw(self.board, "Doe een zet!") else: self.gui.draw(self.board, "Speler twee is aan zet") def game_already_started(self): print("Oeps! Er is al een spel bezig.") self.stop() def move_made(self, x: int, y: int): if self.game_over or self.is_my_turn: return self.is_my_turn = True if self.im_player_one: self.board[y][x] = Cell.O else: self.board[y][x] = Cell.X if self.max_same_cell_row_count(x, y) >= 3: self.game_over = True self.gui.draw(self.board, "Speler twee is gewonnen!") else: self.gui.draw(self.board, "Doe een zet!") def window_close(self): self.stop() def click_cell(self, x: int, y: int): if self.game_over or not self.is_my_turn: return if self.board[y][x] != Cell.EMPTY: return self.is_my_turn = False self.net.make_move(x, y) if self.im_player_one: self.board[y][x] = Cell.X else: self.board[y][x] = Cell.O if self.max_same_cell_row_count(x, y) >= 3: self.game_over = True self.gui.draw(self.board, "Jij bent gewonnen!") else: self.gui.draw(self.board, "Speler twee is aan zet") def max_same_cell_row_count(self, cx: int, cy: int): counts = [] # Iterate top-left, -middle and -right for dx in range(-1, 2): dy = -1 counts.append(self.same_cell_row_count(cx, cy, dx, dy)) # Check left dx = -1 dy = 0 counts.append(self.same_cell_row_count(cx, cy, dx, dy)) return max(counts) def same_cell_row_count(self, cx: int, cy: int, dx: int, dy: int): """Returns the number of same-value cells in a row. Checks both the (dx, dy) direction and its oposite. """ return (self.directed_same_cell_row_count(cx, cy, dx, dy) + 1 + self.directed_same_cell_row_count(cx, cy, -dx, -dy)) def directed_same_cell_row_count(self, cx: int, cy: int, dx: int, dy: int): """Returns the number of same-value cells in a row. Checks the (dx, dy) direction (delta-x, -y). """ center_val = self.board[cy][cx] count = 0 x, y = (cx + dx, cy + dy) if not self.is_on_board(x, y): return count val = self.board[y][x] while val == center_val: count += 1 # Delta-extended-x, -y dex, dey = (dx * (count + 1), dy * (count + 1)) x, y = (cx + dex, cy + dey) if not self.is_on_board(x, y): break val = self.board[y][x] return count def is_on_board(self, x, y): return (x > 0 and x < self.board_size.width and y > 0 and y < self.board_size.height) def stop(self): print("\nExiting...") if self.gui is not None: self.gui.stop() if self.net is not None: self.net.stop() self.stop_game = True def start(self): game_name = input("Game name> ") self.board = [[Cell.EMPTY for x in range(self.board_size.width)] for y in range(self.board_size.height)] size = 500, 500 self.gui = Gui(size, Color("blue"), Color("white"), GuiHandlers(self.click_cell, self.window_close)) self.gui.init() self.gui.draw(self.board, "Wachten op speler 2...") self.net = Net( MqttCommHandlers(self.game_start, self.game_already_started, self.move_made)) self.net.init() self.net.connect(game_name) while not self.stop_game: sleep(0.05)