class TextInput(): def __init__(self, screen, pos, size, font, **kwargs): self.screen = screen self.pos = pos self.size = size self.rect = Rect(self.pos, self.size) self.font = font self.font_height = self.font.get_height() self.command = kwargs.get("command", None) self.maxlines = kwargs.get("maxlines", -1) self.maxlinelength = kwargs.get("maxlinelength", -1) self.focused = False self.highlighted = False self.cursor = Cursor("|", 700, 500, self.pos) self.text = SelectableText(self.screen, "", self.font, self.pos, textwrap=kwargs.get("textwrap", False), maxlinelength=kwargs.get("maxlinelength", -1)) self.update_text("") pygame.key.set_repeat(500, 20) def update_text(self, text): self.text.change_text(text) def get_text(self): return self.text.text.get_text() def update(self, event): significant_event = False mouse_pos = pygame.mouse.get_pos() if event.type == MOUSEBUTTONDOWN and event.button == 1 and self.rect.collidepoint(mouse_pos): self.focused = True self.cursor.start() elif event.type == MOUSEBUTTONDOWN and event.button == 1 and not self.rect.collidepoint(mouse_pos): self.focused = False self.cursor.stop() elif event.type == MOUSEMOTION: if self.rect.collidepoint(mouse_pos): self.highlighted = True else: self.highlighted = False elif event.type == KEYDOWN and self.focused: mod = event.mod mods = pygame.key.get_mods() significant_event = True if event.key == K_BACKSPACE: if self.text.get_selected_text() != None: points = self.text.get_ordered_points() self.cursor.x, self.cursor.y = points[0] self.text.removeslice(points) else: if self.cursor.x > 0: self.text.remove([self.cursor.x - 1, self.cursor.y]) self.cursor.x -= 1 else: if self.cursor.y > 0: self.cursor.x = len(self.text.lines[self.cursor.y - 1]) self.text.remove([-1, self.cursor.y]) self.cursor.y -= 1 elif event.key == K_DELETE: if self.text.get_selected_text() != None: points = self.text.get_ordered_points() self.cursor.x, self.cursor.y = points[0] self.text.removeslice(points) else: self.text.remove((self.cursor.x, self.cursor.y)) elif event.key == K_RETURN: self.text.insertline((self.cursor.x, self.cursor.y)) self.cursor.y += 1 self.cursor.x = 0 #if self.command != None: # self.command() elif event.key == K_LEFT: if self.cursor.x > 0: self.cursor.x -= 1 else: if self.cursor.y > 0: self.cursor.y -= 1 self.cursor.x = len(self.text.lines[self.cursor.y]) elif event.key == K_RIGHT: if self.cursor.x < len(self.text.lines[self.cursor.y]): self.cursor.x += 1 else: if self.cursor.y < len(self.text.lines) - 1: self.cursor.y += 1 self.cursor.x = 0 elif event.key == K_UP: self.cursor.move_up(self.text.size_list) if self.cursor.x > len(self.text.lines[self.cursor.y]): self.cursor.x = len(self.text.lines[self.cursor.y]) - 1 elif event.key == K_DOWN: self.cursor.move_down(self.text.size_list) if self.cursor.x > len(self.text.lines[self.cursor.y]): self.cursor.x = len(self.text.lines[self.cursor.y]) -1 else: if event.unicode != "" and mods in [0, 1, 2, 4096, 8192, 4097, 4098, 8193, 8194]: if self.text.get_selected_text() != None: self.text.replaceslice(self.text.get_ordered_points(), event.unicode) self.cursor.x = self.text.get_ordered_points()[0][0] + 1 self.cursor.y = self.text.get_ordered_points()[0][1] else: self.text.insert((self.cursor.x, self.cursor.y), event.unicode) self.cursor.x += 1 if mods == 0: self.text.selectnone() if significant_event: self.cursor.event() self.change_color() self.text.update(event) def change_color(self): if self.highlighted: self.color = (0, 0, 200) elif self.focused: self.color = (0, 0, 150) else: self.color = (0, 0, 100) def draw(self): self.cursor.x, self.cursor.y = self.text.wrap([self.cursor.x, self.cursor.y]) self.cursor.update() if self.cursor.visible: if self.text.get_selected_text() != None: self.cursor.x = self.text.x2 self.cursor.y = self.text.y2 self.cursor.calc_pixel_pos(self.text.size_list, self.font.get_height()) self.screen.blit(self.font.render(self.cursor.string, 1, (255, 255, 255)), (self.cursor.pixelx, self.cursor.pixely)) pygame.draw.rect(self.screen, self.color, self.rect, 2) self.text.draw()
class TextInput(SelectableText): def __init__(self, screen, **kwargs): super().__init__(screen, **kwargs) self.rect = Rect(0, 0, kwargs.get("height", 0), kwargs.get("width", 0)) self.multiline = kwargs.get("multiline", True) self.cursor = Cursor(height=self.textheight) self.focused = False self.highlighted = False def update(self, event=None): super().update(event) if not None in [self.x2, self.y2]: self.cursor.x_index = self.x2 self.cursor.y_index = self.y2 significant_event = False mouse_pos = pygame.mouse.get_pos() if event.type == MOUSEBUTTONDOWN and event.button == 1 and self.rect.collidepoint(mouse_pos): self.focused = True self.cursor.start() elif event.type == MOUSEBUTTONDOWN and event.button == 1 and not self.rect.collidepoint(mouse_pos): self.focused = False self.cursor.stop() elif event.type == MOUSEMOTION: if self.pressed: significant_event = True if self.rect.collidepoint(mouse_pos): self.highlighted = True else: self.highlighted = False elif event.type == KEYDOWN and self.focused: significant_event = True if event.key == K_BACKSPACE: new_indeces = self.delete_selection() if not new_indeces: self.cursor.x_index -= 1 if self.cursor.x_index < 0: if self.cursor.y_index > 0: self.cursor.y_index -= 1 self.cursor.x_index = len(self.final_lines[self.cursor.y_index].text) self.join_lines(self.cursor.y_index, self.cursor.y_index + 1) else: self.cursor.x_index = 0 else: self.delete((self.cursor.x_index, self.cursor.y_index)) else: self.cursor.x_index, self.cursor.y_index = new_indeces elif event.key == K_DELETE: new_indeces = self.delete_selection() if not new_indeces: if self.cursor.x_index < len(self.final_lines[self.cursor.y_index].text): self.delete((self.cursor.x_index, self.cursor.y_index)) else: if self.cursor.y_index < len(self.final_lines) - 1: self.join_lines(self.cursor.x_index, self.cursor.y_index + 1) else: self.cursor.x_index, self.cursor.y_index = new_indeces elif event.key == K_RETURN: if self.multiline: new_indeces = self.delete_selection() if new_indeces: self.cursor.x_index, self.cursor.y_index = new_indeces self.split_line((self.cursor.x_index, self.cursor.y_index)) self.cursor.x_index = 0 self.cursor.y_index += 1 elif event.key == K_UP: pos = self.get_index_pos((self.cursor.x_index, self.cursor.y_index)) self.cursor.x_index, self.cursor.y_index = self.get_nearest_index((pos[0], pos[1] - self.textheight)) elif event.key == K_DOWN: pos = self.get_index_pos((self.cursor.x_index, self.cursor.y_index)) self.cursor.x_index, self.cursor.y_index = self.get_nearest_index((pos[0], pos[1] + self.lineheight)) elif event.key == K_LEFT: if self.cursor.x_index > 0: self.cursor.x_index -= 1 elif self.cursor.y_index > 0: self.cursor.y_index -= 1 self.cursor.x_index = len(self.final_lines[self.cursor.y_index].text) elif event.key == K_RIGHT: if self.cursor.x_index < len(self.final_lines[self.cursor.y_index].text): self.cursor.x_index += 1 elif self.cursor.y_index < len(self.final_lines) - 1: self.cursor.y_index += 1 self.cursor.x_index = 0 else: new_indeces = self.delete_selection() if new_indeces: self.cursor.x_index, self.cursor.y_index = new_indeces character = event.unicode if len(character) > 0: self.select_none() self.insert((self.cursor.x_index, self.cursor.y_index), character) self.cursor.x_index += 1 if significant_event: self.cursor.event() self.change_color() def change_color(self): if self.highlighted: self.color = (0, 0, 200) elif self.focused: self.color = (0, 0, 150) else: self.color = (0, 0, 100) def draw(self): self.cursor.update() pygame.draw.rect(self.screen, self.color, self.rect, 2) super().draw() self.cursor.draw(self.screen, self.get_index_pos((self.cursor.x_index, self.cursor.y_index)))
class Menu(object): """docstring for Menu""" def __init__(self): self.pantalla = pygame.display.set_mode((600, 704)) self.fondo1 = fondo("Fondo.jpg") self.logo = pygame.sprite.Sprite() self.footPage = pygame.image.load("macro.png").convert_alpha() self.Cursor = Cursor() self.boton1 = Boton("boton3.png", "boton4.png") self.boton2 = Boton("boton5.png", "boton6.png", 300, 350) self.boton3 = Boton("boton7.png", "boton8.png", 300, 450) self.boton4 = Boton("boton1.png", "boton2.png", 500, 600) self.logo = pygame.sprite.Sprite() self.logo = pygame.image.load("LogoGame2.png").convert_alpha() self.visibilidad = True #self.lista_menu = pygame.sprite.Group() self.Dibujar_Menu() def ocultarComponentes(self): self.visibilidad = False def Mostrar_Opciones(self): #self.Cursor.update() if self.boton1.Colision_Cursor(self.pantalla, self.Cursor): if self.boton1.MouseEvento(): self.Iniciar_Juego() if self.boton2.Colision_Cursor(self.pantalla, self.Cursor): if self.boton2.MouseEvento(): self.ocultarComponentes() if self.boton3.Colision_Cursor(self.pantalla, self.Cursor): if self.boton3.MouseEvento(): self.Salir() self.boton1.dibujar(self.pantalla) self.boton2.dibujar(self.pantalla) self.boton3.dibujar(self.pantalla) def Iniciar_Juego(self): nivel1.nivel1() def Mostrar_Puntajes(self): pass def Salir(self): pygame.quit() def Acciones(self): pass def Dibujar_Menu(self): #pygame.mixer.pre_init(44100, -16, 1, 512) pygame.mixer.pre_init(44100, -16, 1, 512) pygame.init() salir = False pygame.mixer.music.load("OST/mainTheme3.mp3") pygame.mixer.music.play() reloj1 = pygame.time.Clock() while salir != True: for event in pygame.event.get(): if event.type == pygame.QUIT: salir = True reloj1.tick(30) self.Cursor.update() self.fondo1.update(self.pantalla, False) if self.visibilidad: self.pantalla.blit(self.logo, (90, 100)) self.pantalla.blit(self.footPage, (125, 650)) self.Mostrar_Opciones() else: self.boton4.dibujar(self.pantalla) if self.boton4.Colision_Cursor( self.pantalla, self.Cursor) and self.boton4.MouseEvento(): self.visibilidad = True pygame.display.flip() pygame.quit()
if event.key == pygame.K_SPACE: #shoot() level.decrease_health(100) if event.key == pygame.K_ESCAPE: running = False if event.type == pygame.MOUSEBUTTONDOWN: array = pygame.mouse.get_pressed() if array[0]: shoot() if array[1]: cursor.calibrate() if array[2]: pygame.quit() cursor.update() """ Clear and background """ screen.fill((255, 255, 255)) screen.blit(background, (0, 0)) if GameStateEnum.mainmenu == gamestate.getState(): """ Update """ """ Draw """ popup.draw(screen) pass elif GameStateEnum.running == gamestate.getState(): """ Update """ level.update()
def main_game_loop(self): # Define the entity groups character_entities = pygame.sprite.Group() # All character entities (including Player.py) built_entities = pygame.sprite.Group() # Anything the player has built # Build the level level = Level() level.generate(self.tile_cache) # Create the player player_sprites = "data/images/player/" camera = Camera(main_camera, level.width * self.tile_size, level.height * self.tile_size, self.window_width, self.window_height) self.player = Player(32, 32, player_sprites, self.tile_size, self.tile_size, 2, camera) character_entities.add(self.player) # Create cursor entity for better collisions cursor = Cursor() game_running = True up, down, left, right = 0, 0, 0, 0 while game_running: # Reset game variables mouse_clicked = False for event in pygame.event.get(): if event.type == pygame.QUIT: quit_game() # Key down events if event.type == pygame.KEYDOWN: if event.key in (pygame.K_UP, pygame.K_w): up = 1 if event.key in (pygame.K_DOWN, pygame.K_s): down = 1 if event.key in (pygame.K_LEFT, pygame.K_a): left = 1 if event.key in (pygame.K_RIGHT, pygame.K_d): right = 1 # Key up events if event.type == pygame.KEYUP: if event.key in (pygame.K_UP, pygame.K_w): up = 0 if event.key in (pygame.K_DOWN, pygame.K_s): down = 0 if event.key in (pygame.K_LEFT, pygame.K_a): left = 0 if event.key in (pygame.K_RIGHT, pygame.K_d): right = 0 cursor.update() for tile in level.terrain: self.screen.blit(tile.image, self.player.camera.apply(tile)) for tile in level.obstacles: self.screen.blit(tile.image, self.player.camera.apply(tile)) for character in character_entities: self.screen.blit(character.image, self.player.camera.apply(character)) self.player.update(up, down, left, right, level.obstacles) pygame.display.flip() self.main_menu_loop()
class Game: def __init__(self): self.board = Board(ROWS, COLUMNS) self.gui = GUI(ROWS, COLUMNS, SIZE, self.board) self.rules = Rules() self.cursor = Cursor() self.player1 = Player(1) self.player2 = AIPlayer(2, self.rules, self.board) self.currentPlayer = self.assign_player() self.gameOver = False self.menuFlag = False def assign_player(self): a = random.randint(0, 1) if a == 0: self.gui.next_move_message(self.player1.get_id()) return self.player1 else: self.gui.next_move_message(self.player2.get_id()) return self.player2 def switch_players(self): if self.currentPlayer == self.player1: self.currentPlayer = self.player2 else: self.currentPlayer = self.player1 self.gui.next_move_message(self.currentPlayer.get_id()) def reset(self): self.menuFlag = False self.board.reset() def change_rules(self, rule): if rule == 1: self.rules = Rules() elif rule == 2: self.rules = DiagonalOnly() else: self.rules = RowsColumnsOnly() self.reset() def update_cursor(self, event): x = event.pos[0] y = event.pos[1] self.cursor.update(x, y) def mouse_motion(self): if self.gameOver is False and self.menuFlag is False: if self.gui.are_buttons_hovered(self.cursor.gety()): self.gui.buttons_hovered(self.cursor.getx()) else: self.gui.draw_gui(self.board) elif self.menuFlag: if self.gui.are_rules_hovered(self.cursor.getx(), self.cursor.gety()): self.gui.rules_hovered(self.cursor.getx(), self.cursor.gety()) else: self.gui.draw_gui(self.board) def move_made(self): if self.rules.winning_move(self.board.get_board(), self.currentPlayer.get_id(), self.board.get_columns(), self.board.get_rows()): self.gameOver = True self.gui.winning_move_message(self.currentPlayer.get_id()) elif self.board.is_full(): self.gui.draw_message() self.gameOver = True else: self.switch_players() #print(self.board.get_board()) def mouse_clicked(self): if self.gameOver is False and self.menuFlag is False: if self.gui.are_buttons_hovered(self.cursor.gety()): col = int(math.floor(self.cursor.getx() / self.gui.get_size())) if self.currentPlayer.make_move(self.board, col): self.move_made() else: self.gui.not_valid_loc_message(self.currentPlayer.get_id()) self.gui.draw_gui(self.board) elif self.menuFlag: if self.gui.are_rules_hovered(self.cursor.getx(), self.cursor.gety()): rule = self.gui.get_rule(self.cursor.getx(), self.cursor.gety()) self.change_rules(rule) self.gui.shut_rules() self.gameOver = self.menuFlag = False self.reset() if self.gui.reset_hovered(self.cursor.getx(), self.cursor.gety()): self.board.reset() self.assign_player() self.gameOver = self.menuFlag = False if self.gui.are_options_hovered(self.cursor.getx(), self.cursor.gety()): self.gui.options_hovered(self.menuFlag) self.menuFlag = not self.menuFlag self.gui.draw_gui(self.board) def start_game(self): while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if self.currentPlayer.get_type() == "player": if event.type == pygame.MOUSEMOTION: self.update_cursor(event) self.mouse_motion() elif event.type == pygame.MOUSEBUTTONDOWN: self.update_cursor(event) self.mouse_clicked() elif self.currentPlayer.get_type() == "AI": if not self.gameOver and not self.menuFlag: if self.currentPlayer.make_move(self.board, 0): self.move_made() else: self.gui.not_valid_loc_message( self.currentPlayer.get_id()) self.gui.draw_gui(self.board) else: self.currentPlayer = self.player1
class Game(arcade.Window): def __init__(self): super().__init__(WIDTH, HEIGHT, NAME) arcade.set_background_color(arcade.color.WHITE) self.SERVER = socket.gethostbyname(socket.gethostname()) self.PORT = 5050 self.ADDR = (self.SERVER, self.PORT) self.FORMAT = 'utf-8' try: self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.client.setblocking(1) self.client.connect(self.ADDR) except: pass self.board_draw = Board() self.board = { '7': ' ', '8': ' ', '9': ' ', '4': ' ', '5': ' ', '6': ' ', '1': ' ', '2': ' ', '3': ' ' } self.button_list = [] self.popup_list = [] self.cursor = Cursor() self.client_ID = None self.my_turn = False self.game_over = False #SERVER REQUEST BOOLS self.board_request = False self.ID_request = False self.player_2 = False self.request_reset = False self.reset_state = False self.clear_state = False self.winner = None self.popup = Popup(WIDTH / 2, HEIGHT / 2 - HEIGHT / 4, 1) self.game_over_popup = Popup(WIDTH / 2, HEIGHT / 2 - HEIGHT / 4, 2) self.restart_popup = Popup(WIDTH / 2, HEIGHT / 2 - HEIGHT / 2.5, 3) self.popup_list.append(self.restart_popup) for x in range(1, 10): button = Button(x) self.button_list.append(button) def col_circle_square(self, tx, ty, tr, cx, cy, cr): dx = tx - cx dy = ty - cy distance = math.sqrt(dx * dx + dy * dy) if distance < tr + cr: return True def detect_collision(self, rect1, rect2): if (rect1[0] < rect2[0] + rect2[2] and rect1[0] + rect1[2] > rect2[0] and rect1[1] < rect2[1] + rect2[3] and rect1[1] + rect1[3] > rect2[1]): return True def decode_board(self, msg): utf_json = msg.decode(self.FORMAT) json_list = json.loads(utf_json) return json_list def clear_board(self): for x in self.board: if self.board[str(x)] == 'X' or self.board[str(x)] == 'O': self.board[str(x)] = " " def clear_game(self): try: if self.clear_state: msg = '!c' self.client.send(msg.encode(self.FORMAT)) reply = self.client.recv(16) reply_decode = reply.decode(self.FORMAT) if reply_decode == '!r': self.clear_board() self.game_over = False self.clear_state = False if self.client_ID == 2: self.my_turn = False except Exception as e: print(e) def check_win(self): print('2') try: if not self.clear_state: msg = '!w' self.client.send(msg.encode(self.FORMAT)) reply = self.client.recv(128) reply_decode = reply.decode(self.FORMAT) if reply_decode == 'X': self.winner = 'X' self.game_over = True elif reply_decode == 'O': self.winner = 'O' self.game_over = True elif reply_decode == '!p': self.game_over = False elif reply_decode == '!o': self.game_over = True except Exception as e: print(e) def player_2_connected(self): try: if self.client_ID == 1: if not self.player_2: msg = '!p' self.client.send(msg.encode(self.FORMAT)) reply = self.client.recv(2) if reply.decode(self.FORMAT) == '!t': self.player_2 = True else: self.player_2 = False elif self.client_ID == 2: self.player_2 = True except Exception as e: print(e) def send_board_request(self): print('4') try: if not self.board_request: msg = '!board' request = msg.encode(self.FORMAT) self.client.send(request) new_msg = self.client.recv(92) utf_string = new_msg.decode(self.FORMAT) json_list = json.loads(utf_string) self.board = json_list[0] self.board_request = True except: traceback.print_exc() def send_ID_request(self): try: if not self.client_ID: msg = '!ID' request = msg.encode(self.FORMAT) self.client.send(request) new_msg = self.client.recv(6) message = new_msg.decode(self.FORMAT) self.client_ID = int(message) except Exception as e: pass def request_turn(self): print('6') try: if not self.my_turn: if self.client_ID: if self.client_ID == 1: msg = '!t1' else: msg = '!t2' self.client.send(msg.encode(self.FORMAT)) reply = self.client.recv(2) decoded_reply = reply.decode(self.FORMAT) if decoded_reply == '!t': self.my_turn = True self.board_request = False else: self.my_turn = False self.check_win() except Exception as e: print(e) def on_draw(self): arcade.start_render() self.board_draw.draw() for button in self.button_list: button.draw() self.cursor.draw() if self.client_ID == 1: if not self.my_turn or not self.player_2: if not self.game_over: self.popup.draw() elif self.client_ID == 2: if not self.my_turn: if not self.game_over: self.popup.draw() if self.game_over: self.game_over_popup.draw() self.restart_popup.draw() arcade.finish_render() def update(self, delta_time: float): self.cursor.update(self._mouse_x, self._mouse_y) self.player_2_connected() self.send_ID_request() if not self.clear_state: self.request_turn() self.send_board_request() elif self.clear_state: self.clear_game() for button in self.button_list: button.update(self.board) self.restart_popup.update(self.cursor) def on_mouse_press(self, x: float, y: float, button: int, modifiers: int): if self.my_turn and not self.game_over: if self.player_2: if button == 1: c = self.cursor for button in self.button_list: if button.value == button.B: if self.col_circle_square(button.x, button.y, button.r, c.x, c.y, c.r): col_list = [] col_list.append(button) if (len(col_list) > 1): col_list.RemoveRange( 0, col_list.count() - 1) com = '!sub' com_encode = com.encode(self.FORMAT) self.client.send(com_encode) msg = str(col_list[0].ID) self.client.send(msg.encode(self.FORMAT)) col_list.clear() self.my_turn = False self.board_request = False elif self.game_over: if self.restart_popup.colliding: self.clear_state = True def on_mouse_drag(self, x: float, y: float, dx: float, dy: float, buttons: int, modifiers: int): pass '''for button in self.button_list: if button.dragging: button.x, button.y = self.cursor.x, self.cursor.y''' def on_mouse_release(self, x: float, y: float, button: int, modifiers: int): pass '''for button in self.button_list: