class Button(): '''Manages Button creation and click events''' def __init__(self, toState, image, x, y, w, h): '''Initializes button's draw rectangle, image, isDown state and click event transition state''' self.rect = Rect(x, y, w, h) self.image = image self.toState = toState self.isDown = False def checkCollision(self, mousePos): '''Checks if the current mouse position is inside the button's rectangle''' if self.rect.collidepoint(mousePos): return True else: return False def checkClicked(self, pygame): '''Checks if the current mouse is inside the button and a left click has occurred''' mousePos = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() if self.checkCollision(mousePos) and click[0] == 1: return True else: return False def update(self, pygame, stateFunc): '''button's update loop: constantly checks for click events''' click = pygame.mouse.get_pressed() if self.checkClicked(pygame): self.isDown = True elif self.isDown and click[0] == 0: stateFunc(self.toState) self.isDown = False
class VueForOverlay(object): """@summary: Classe provoquant un affichage d'overlay quand survolé par la souris""" def __init__(self, fenetre, posX, posY, width, height, objectWithOverlay): """@summary: initialise une vue déclenchant un overlay. @fenetre: la fenêtre pygame @type: pygame fenêtre @posX: la position posX du composant @type: int @posY: la position posY du composant @type: int @width: la largeur du composant @type: int @height: la hauteur du composant @type: int @objectWithOverlay: l'object qui a un attribut overlay de type Overlay @type: Object""" self.posX = posX self.posY = posY self.width = width self.height = height self.fenetre = fenetre self.hitbox = Rect(posX, posY, width, height) self.objectWithOverlay = objectWithOverlay self.objectWithOverlay.overlay.fenetre = fenetre def isMouseOver(self, mouseXY): """@summary: Indique si la souris survole le composant @mouseXY: la position de la souris @type: tableau de coordonnée [int x, int y] @return: True si les coordonnées passées en paramètres sont sur le composant décrit""" return self.hitbox.collidepoint(mouseXY)
class ButtonRect: """Button class for add players based on the Command pattern.""" def __init__(self, x, y, w, h, command): """ Constructor """ self.rect = Rect(x, y, w, h) self.command = command def handleMouseDown(self, x, y): if self.rect.collidepoint(x, y): if self.command <> None: self.command.do() def draw(self, surface): # TODO : use picture here. # This method could also be implemented by subclasses. pygame.draw.rect(surface, (100, 100, 100), self.rect)
class ButtonCircle: """Button class for add players based on the Command pattern.""" def __init__(self, x, y, r, command, color=(100,100,100)): """ Constructor """ self.r = r self.rect = Rect(x-r, y-r, r*2, r*2) self.command = command self.color = color def handleMouseDown(self, x, y): if self.rect.collidepoint(x, y): if self.command <> None: self.command.do() def draw(self, surface): # TODO : use picture here. # This method could also be implemented by subclasses. pygame.draw.circle(surface, self.color, (self.rect.x, self.rect.y), self.r)
def MouseInside(self, x, y): r = Rect(self.pos, (self.width, self.height)) return r.collidepoint((x, y))
if (int(lectura) > 900 and puedeTocarSonido): playsound("sonido.mp3", False) # Detenemos la reproducción de sonido cuando empezó a tocar el sonido. puedeTocarSonido = False # En mi caso, vuelvo a habilitar el sonido cuando el sensor baja a menos de 100. if (int(lectura) < 100): puedeTocarSonido = True # Luego, revisamos los eventos, lo que corresponde al input del usuario. for event in pygame.event.get(): # Este evento corresponde a cuando el usuario aprieta la "X" de la aplicación. if event.type == pygame.QUIT: done = True # Este evento corresponde a cuando se apreta un botón del mouse. # El 1 nos dice que fue el botón izquierdo. if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: mpos = pygame.mouse.get_pos( ) # Esto nos retorna la posición (x, y) del click. # La función colliderpoint(mpos) nos retorna verdadero si el # usuario hizo click dentro del botón respectivo. if on_position.collidepoint(mpos): arduino.write('1'.encode()) if off_position.collidepoint(mpos): arduino.write('0'.encode()) # Para dibujar lo que escribimos en pantalla, debemos usar flip(). pygame.display.flip()
class Square: def __init__(self, pos, piece, win, isIt): self.pos = pos self.piece = piece self.isFull = isIt self.clicked = False self.highlightme = False self.win = win self.square = Rect(self.pos[0], self.pos[1], 80, 80) self.surface = pygame.Surface((70, 70)) self.surface.set_alpha(128) self.surface.fill((255, 0, 0)) def show(self): if self.piece: self.win.blit(self.piece.img, self.pos) # turn on the highlightme of all potential spots and return a list of the potiential spots def show_moves(self, boardDict): if self.isFull: return self.piece.moves(self.pos, self.win, boardDict) return [] # highlight the square def highlight(self): if self.highlightme: self.win.blit(self.surface, (self.pos[0] + 5, self.pos[1] + 5)) if self.clicked: self.win.blit(self.surface, (self.pos[0] + 5, self.pos[1] + 5)) # when we click a square we need to highlight the clicked square and then get info on potential moves def update_squares(self, board): self.win.blit(self.surface, (self.pos[0] + 5, self.pos[1] + 5)) # if the square we clicked is the same as the previous, just keep the square highglighted if self.pos == board.clickedSquares[board.turn].pos: board.pot_moves = self.show_moves(board.dict) # if the square we clicked is a potential move square, we need to update our clicked square and move our piece elif self.pos in board.pot_moves: self.update_board(board) # update the board print(self.pos) self.release_highlight(board) # release all old highlights # else do .... else: board.clickedSquares[board.turn].clicked = False board.clickedSquares[board.turn].highlightme = False self.release_highlight(board) board.pot_moves = self.show_moves(board.dict) board.clickedSquares[board.turn] = self board.clickedSquares[board.turn].clicked = True board.clickedSquares[board.turn].highlightme = True def check_castling(self, board): if isinstance(board.clickedSquares[board.turn].piece, King): if board.clickedSquares[board.turn].piece.col == 0: if not board.clickedSquares[board.turn].piece.has_moved and ( self.pos in board.clickedSquares[ board.turn].piece.castle_moves_white): moveRook = board.dict[board.clickedSquares[ board.turn].piece.castle_moves_white[self.pos][0]] moveRook.piece = board.dict[board.clickedSquares[ board.turn].piece.castle_moves_white[self.pos] [1]].piece moveRook.isFull = True board.dict[board.clickedSquares[board.turn].piece. castle_moves_white[self.pos][1]].piece = None board.dict[board.clickedSquares[board.turn].piece. castle_moves_white[self.pos][1]].isFull = False else: if not board.clickedSquares[board.turn].piece.has_moved and ( self.pos in board.clickedSquares[ board.turn].piece.castle_moves_black): moveRook = board.dict[board.clickedSquares[ board.turn].piece.castle_moves_black[self.pos][0]] moveRook.piece = board.dict[board.clickedSquares[ board.turn].piece.castle_moves_black[self.pos] [1]].piece moveRook.isFull = True board.dict[board.clickedSquares[board.turn].piece. castle_moves_black[self.pos][1]].piece = None board.dict[board.clickedSquares[board.turn].piece. castle_moves_black[self.pos][1]].isFull = False # update the clicked square and move piece def update_board(self, board): # here we will check if the king or the rooks have moved. this is needed for castling functionality chess_sound.play() self.check_castling(board) if isinstance(board.clickedSquares[board.turn].piece, Rook) or isinstance( board.clickedSquares[board.turn].piece, King): board.clickedSquares[board.turn].piece.has_moved = True self.piece = board.clickedSquares[board.turn].piece self.isFull = True # set that the square is now full self.clicked = False # clicked is false board.clickedSquares[board.turn].piece = None board.clickedSquares[board.turn].clicked = False board.clickedSquares[board.turn].isFull = False board.clickedSquares[board.turn].highlightme = False board.clickedSquares[board.turn] = self board.clickedSquares[board.turn].highlightme = False board.clickedSquares[board.turn].clicked = False if board.turn == WHITE: board.turn = BLACK else: board.turn = WHITE self.release_highlight(board) # release the highlighted squares board.pot_moves = [] # clear our potential moves def release_highlight(self, board): for move in board.pot_moves: if move in board.dict: board.dict[move].highlightme = False def squareClicked(self, coords, board): if self.square.collidepoint(coords) and ( (self.piece == None) or (self.piece.col == board.turn) or (self.pos in board.pot_moves)): if pygame.mouse.get_pressed()[0]: self.clicked = True self.highlightme = True
class Cell(): '''Manages the Cell's state, values, and event logic''' def __init__(self, x=0, y=0, w=0, h=0, xLoc=0, yLoc=0): '''Initializes the cell's location, image, font, grid location, and game values''' self.rect = Rect(x, y, w, h) self.image = None self.flippedImage = None self.font = None self.xLoc = xLoc self.yLoc = yLoc self.isVisible = False self.isBomb = False self.justDown = False self.isDown = False self.value = 0 # Flagging a Cell self.isFlagged = False self.isRightDown = False def createXMLElement(self, parent): '''generates an XML element that represents the given Cell''' element = SubElement(parent, "Cell") element.attrib = { "rX": str(self.rect.x), "rY": str(self.rect.y), "rW": str(self.rect.w), "rH": str(self.rect.h), "X": str(self.xLoc), "Y": str(self.yLoc), "isFlagged": str(self.isFlagged), "isVisible": str(self.isVisible), "isBomb": str(self.isBomb), "value": str(self.value) } def createCell(self, xmlNode): '''generates a Cell from a given Cell XML Element''' try: x = int(xmlNode.attrib["rX"]) y = int(xmlNode.attrib["rY"]) w = int(xmlNode.attrib["rW"]) h = int(xmlNode.attrib["rH"]) self.rect = Rect(x, y, w, h) self.xLoc = int(xmlNode.attrib["X"]) self.yLoc = int(xmlNode.attrib["Y"]) flag = xmlNode.attrib["isFlagged"] if flag == "False": self.isFlagged = False else: self.isFlagged = True vis = xmlNode.attrib["isVisible"] if vis == "False": self.isVisible = False else: self.isVisible = True bomb = xmlNode.attrib["isBomb"] if bomb == "False": self.isBomb = False else: self.isBomb = True temp = xmlNode.attrib["value"] if not temp == "X": temp = int(temp) self.value = temp except: return False return True def checkCollision(self, mousePos): '''Checks if the mouse position is contained within the cell's rectangle''' if self.rect.collidepoint(mousePos): return True else: return False def setVisible(self): '''sets the cell as visible and changes the artwork representing the cell''' self.isFlagged = False self.isVisible = True self.image = self.flippedImage self.justDown = False def update(self, pygame, window, isGameOver): '''Cell update loop: checks for click events and manages content visibility''' text = "" # Check if the artwork needs to be initialized if self.image == None: self.font = pygame.font.Font(None, 42) self.flippedImage = pygame.image.load( "minesweeper/assets/button_flipped.png").convert() if self.isVisible and not self.isBomb: self.image = self.flippedImage else: self.image = pygame.image.load( "minesweeper/assets/button_normal.png").convert() # If not visible (and game not over) check if the state needs to be updated if not self.isVisible and not isGameOver: mousePos = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() # Check Right Click Events if self.checkCollision( mousePos) and click[2] == 1 and not self.isRightDown: self.isFlagged = (not self.isFlagged) self.isRightDown = True elif self.checkCollision( mousePos) and click[2] == 0 and self.isRightDown: self.isRightDown = False # Check Left Click Events elif self.checkCollision(mousePos) and click[0] == 1: self.isDown = True elif self.checkCollision( mousePos) and click[0] == 0 and self.isDown: self.justDown = True self.isDown = False else: self.isDown = False else: if self.justDown: self.setVisible() if not self.value == 0: text = str(self.value) # Button Image window.blit(self.image, [self.rect.x, self.rect.y]) if self.isFlagged: # Flag Value label = self.font.render("?", True, (0, 0, 0)) window.blit(label, (self.rect.x + 9, self.rect.y + 5)) else: # Text Value label = self.font.render(text, True, (0, 0, 0)) window.blit(label, (self.rect.x + 9, self.rect.y + 5))
def main(): """ メインルーチン """ colors = [(255, 0, 0), (255, 64, 0), (255, 201, 38), (35, 140, 0), (0, 128, 255), (163, 0, 217), (255, 77, 255), (255, 255, 255)] color = colors[0] background_image \ = pygame.image.load("images/background/wall0.png") ball_image = pygame.image.load("ball.png") ball_image = pygame.transform.scale(ball_image, (30, 30)) palette_image = pygame.image.load("images/bg_palette.png") palette_image = pygame.transform.scale(palette_image, (800, 54)) palette_rect = Rect(0, 0, 800, 54) button_images = [] for index in range(8): path = "images/button/color" + str(index) + ".png" button_images.append(pygame.image.load(path)) current_line = None mouse_pos = (0, 0) mousedown = False count = 0 engine = Engine(0, 0, 800, 500, 0, 9.8) while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() elif event.type == MOUSEBUTTONDOWN: if palette_rect.collidepoint(event.pos): pindex = floor(event.pos[0] / 72) if 0 <= pindex < 8: color = colors[pindex] else: mousedown = True mouse_pos = event.pos elif event.type == MOUSEMOTION: if mousedown: current_line = (mouse_pos, event.pos, color) else: current_line = None elif event.type == MOUSEBUTTONUP: if mousedown and not \ (mouse_pos[0] == event.pos[0] and \ mouse_pos[1] == event.pos[1]): line_entity = LineEntity(mouse_pos[0], mouse_pos[1], event.pos[0], event.pos[1]) line_entity.color = color engine.entities.append(line_entity) mousedown = False current_line = None # 100カウント毎にボールを落とす if count % 100 == 0: circle = CircleEntity(randint(0, 600)+100, 0, 10) circle.color = color engine.entities.append(circle) count += 1 engine.step(0.01) # パレットと未確定の線の描画 for ypos in range(0, 500, 150): for xpos in range(0, 800, 150): SURFACE.blit(background_image, (xpos, ypos)) SURFACE.blit(palette_image, (0, 0)) for index in range(8): SURFACE.blit(button_images[index], (index*72, 0)) if current_line: pygame.draw.line(SURFACE, current_line[2], current_line[0], current_line[1], 3) # ボールと線の描画 for entity in engine.entities: if entity.shape == SHAPE_CIRCLE: pos = (int(entity.xpos), int(entity.ypos)) rect = ball_image.get_rect() rect.center = pos SURFACE.blit(ball_image, rect.topleft) elif entity.shape == SHAPE_LINE: pos0 = (int(entity.pos0[0]), int(entity.pos0[1])) pos1 = (int(entity.pos1[0]), int(entity.pos1[1])) pygame.draw.line(SURFACE, entity.color, pos0, pos1, 3) pygame.display.update() FPSCLOCK.tick(20)