def recv_image_data(self, img_size, img_sel): imgView = (self.img_view_1 if img_sel else self.img_view_0) if img_size > self.img_max_size: raise RuntimeError( "Expected size {} exceeds buffer size {}".format( img_size, self.img_max_size)) return -1, imgView try: utils.recv_data_into(self.sock, imgView[:img_size], img_size) except: return -1, imgView # Read the final handshake try: cmd = utils.recv_data(self.sock, 5).decode('ascii') except: return -1, imgView if cmd != 'enod!': raise RuntimeError( "Unexpected server reply. Expected 'enod!', got '{}'".format( cmd)) return -1, imgView # # Transaction is done, we now process/display the received image # img = jpeg_decode_func(img_view[:img_size]) return 0, imgView
def __init__(self, parent=None, admin=False): QtGui.QMainWindow.__init__(self, parent) self.setupUi(self) header_labels = ('Pseudo', 'Score') self.tblScores.setColumnCount(2) self.tblScores.setHorizontalHeaderLabels(header_labels) self.tblScores.horizontalHeader().setResizeMode(QHeaderView.Stretch) # Bind buttons self.btnLeave.clicked.connect(self.btnLeave_clicked) if not admin: self.btnEdit.hide() self.btnDelete.hide() # Get score list utils.send_data(utils.Global.sock_server, commands.CMD_GET_SCORES) scores = utils.recv_data(utils.Global.sock_server) self.tblScores.setRowCount(len(scores)) row = 0 for (login, score) in scores: self.tblScores.setItem(row, 0, QTableWidgetItem(login)) self.tblScores.setItem(row, 1, QTableWidgetItem(str(score))) row = row + 1
def btnInscription_clicked(self): username = self.edtUsername.text() password = self.edtPassword.text() confirmPassword = self.edtConfirmPassword.text() if password != confirmPassword: QMessageBox.about(self, 'Erreur', 'Les mots de passe sont différents !') else: utils.send_data(utils.Global.sock_server, commands.CMD_INSCRIPTION) utils.send_data(utils.Global.sock_server, [username, password]) response = utils.recv_data(utils.Global.sock_server) if response == commands.CMD_OK: QMessageBox.about(self, 'Inscription', 'Vous êtes maintenant inscrit !') self.close() else: QMessageBox.about(self, 'Erreur', 'Un erreur est survenue !')
def refresh(self): # Get current game utils.send_data(utils.Global.sock_server, commands.CMD_GET_GAME) utils.send_data(utils.Global.sock_server, utils.Global.login) game = utils.recv_data(utils.Global.sock_server) if game == None: QMessageBox.about( self, 'Erreur', "La partie n'existe plus ! Le créateur a dû déserter !") self.parent.refresh() self.close() return self.game = game self.lblGameName.setText(game.name) self.tblPlayers.clear() for player in game.players: self.tblPlayers.addItem(player)
def __init__(self, parent=None, game=None): QtGui.QMainWindow.__init__(self, parent) self.setupUi(self) self.parent = parent self.game = game # Disable creation button self.btnCreateGame.setEnabled(False) self.sbxNbMaxPlayers.setRange(1, 12) # Fill the game types combobox types = ['FFA'] self.cbxGameType.addItems(types) # Get maps and fill the map combobox utils.send_data(utils.Global.sock_server, commands.CMD_GET_MAPS) nb_of_maps = utils.recv_data(utils.Global.sock_server) maps = [] for i in range(nb_of_maps): maps.append(str(i + 1)) self.cbxGameMap.addItems(maps) # Bind events self.edtGameName.textChanged.connect(self.text_changed) self.btnCancel.clicked.connect(self.btnCancel_clicked) if game == None: self.btnCreateGame.clicked.connect(self.btnCreateGame_clicked) else: self.btnCreateGame.clicked.connect(self.btnEditGame_clicked) self.btnCreateGame.setText("Modifier") self.edtGameName.setText(self.game.name) self.sbxNbMaxPlayers.setValue(int(self.game.nb_max_players)) type_index = self.cbxGameType.findText(self.game.type, QtCore.Qt.MatchFixedString) self.cbxGameType.setCurrentIndex(type_index) map_index = self.cbxGameMap.findText(str(self.game.map), QtCore.Qt.MatchFixedString) self.cbxGameMap.setCurrentIndex(map_index) self.edtGamePassword.setText(self.game.password)
def btnConnection_clicked(self): username = self.edtUsername.text() password = self.edtPassword.text() utils.send_data(utils.Global.sock_server, commands.CMD_CONNECTION) utils.send_data(utils.Global.sock_server, [username, password]) response = utils.recv_data(utils.Global.sock_server) if response == commands.CMD_OK: utils.Global.login = username # Launch game socket utils.connect_to_server_game() utils.send_data(utils.Global.sock_game, commands.CMD_STOCK_SOCK_GAME) utils.send_data(utils.Global.sock_game, username) utils.Global.game_thread = GameThread() utils.Global.game_thread.start() display_games_window = DisplayGamesWindow(self) display_games_window.show() self.hide() else: QMessageBox.about(self, 'Erreur', 'Une erreur est survenue')
def refresh(self): # Get games list utils.send_data(utils.Global.sock_server, commands.CMD_GET_GAMES) games = utils.recv_data(utils.Global.sock_server) self.tblGames.clear() header_labels = ('Nom', 'Nombre de joueurs', 'Type', 'Carte', 'En cours ?', 'Mot de passe ?') self.tblGames.setColumnCount(6) self.tblGames.setHorizontalHeaderLabels(header_labels) self.tblGames.horizontalHeader().setResizeMode(QHeaderView.Stretch) self.tblGames.setRowCount(len(games)) self.passwords.clear() row = 0 for game in games: self.tblGames.setItem(row, 0, QTableWidgetItem(game.name)) self.tblGames.setItem(row, 1, QTableWidgetItem(str(len(game.players)) + "/" + str(game.nb_max_players))) self.tblGames.setItem(row, 2, QTableWidgetItem(game.type)) self.tblGames.setItem(row, 3, QTableWidgetItem(str(game.map))) self.tblGames.setItem(row, 4, QTableWidgetItem('Oui' if game.is_running else 'Non')) self.tblGames.setItem(row, 5, QTableWidgetItem('Non' if game.password == '' else 'Oui')) self.passwords.append(game.password) row = row + 1
def run(self): colors = [] logins = [] id = 1 for player in self.players: colors.append((id * random.randint(0, 255) % 255, id * random.randint(0, 255) % 255, id * random.randint(0, 255) % 255)) logins.append(player.login) id = id + 1 for player in self.players: utils.send_data(player.sock, colors) utils.send_data(player.sock, logins) running = True while running: players_grid = [] idKill = [] idLost = [] for player in self.players: idKill.append(utils.recv_data(player.sock)) idLost.append(utils.recv_data(player.sock)) player_grid = utils.recv_data(player.sock) players_grid.append(player_grid) send_grid = players_grid[0] for grid in players_grid: for i in range(96): for j in range(96): if grid[i][j] != 0 and send_grid[i][j] == 0: send_grid[i][j] = grid[i][j] win = [] scores = [] for player in self.players: utils.send_data(player.sock, idKill) utils.send_data(player.sock, idLost) utils.send_data(player.sock, send_grid) scores.append(utils.recv_data(player.sock)) win.append(utils.recv_data(player.sock)) tmp = False for w in win: if w: tmp = True else: tmp = False if tmp: for player in self.players: utils.send_data(player.sock, True) running = False else: for player in self.players: utils.send_data(player.sock, False) for i in range(len(self.players)): database.Database.update_scores(self.players[i].login, scores[i])
def run(self): while True: try: command = utils.recv_data(utils.Global.sock_game) except Exception as e: break if command == None: break if command == commands.CMD_LAUNCH_GAME: id = utils.recv_data(utils.Global.sock_game) map = utils.recv_data(utils.Global.sock_game) colors = utils.recv_data(utils.Global.sock_game) players = utils.recv_data(utils.Global.sock_game) screen = pygame.display.set_mode((700, 480)) pygame.display.set_caption("Multitron") background = pygame.Surface(screen.get_size()) background = background.convert() background.fill((10, 198, 198)) wallImage = pygame.image.load("images/wall.png").convert() DOWN = 1 RIGHT = 2 LEFT = 3 UP = 4 PLAYER_SIZE = 5 WALL_SIZE = 30 clock = pygame.time.Clock() playersGrid = [] for i in range(96): playersGrid.append([]) for j in range(96): playersGrid[i].append(0) playerImage = pygame.image.load("images/player.png").convert() x = random.randint(10, 85) * 5 y = random.randint(10, 85) * 5 tmpY = math.floor(y / WALL_SIZE) tmpX = math.floor(x / WALL_SIZE) while map[tmpY][tmpX] != 0: x = random.randint(10, 85) * 5 y = random.randint(10, 85) * 5 tmpY = math.floor(y / WALL_SIZE) tmpX = math.floor(x / WALL_SIZE) direction = DOWN #random.seed(1) pygame.font.init() myfont = pygame.font.Font(None, 50) myfontScore = pygame.font.Font(None, 40) fontPlayerss = pygame.font.Font(None, 25) lose = False win = False score = 0 idEnemy = -1 running = True wait = True pygame.mixer.init() son = pygame.mixer.Sound("sounds/music.wav") son.play() while running: clock.tick(utils.fps) tmpX = math.floor(x / PLAYER_SIZE) tmpY = math.floor(y / PLAYER_SIZE) if not lose and not win: playersGrid[tmpX][tmpY] = id if direction == DOWN: y += PLAYER_SIZE elif direction == RIGHT: x += PLAYER_SIZE elif direction == LEFT: x -= PLAYER_SIZE elif direction == UP: y -= PLAYER_SIZE # Check wall collision tmpY = math.floor(y / WALL_SIZE) tmpX = math.floor(x / WALL_SIZE) if map[tmpY][tmpX] == 1: lose = True score = score - 150 # Check tail collision tmpY = math.floor(y / PLAYER_SIZE) tmpX = math.floor(x / PLAYER_SIZE) if playersGrid[tmpX][tmpY] == id: lose = True score = score - 200 # Check players collision elif playersGrid[tmpX][tmpY] != 0: lose = True score = score - 100 idEnemy = playersGrid[tmpX][tmpY] for event in pygame.event.get(): if event.type == QUIT: pygame.quit() if event.type == KEYDOWN: if event.key == K_RIGHT and direction != LEFT: direction = RIGHT if event.key == K_LEFT and direction != RIGHT: direction = LEFT if event.key == K_UP and direction != DOWN: direction = UP if event.key == K_DOWN and direction != UP: direction = DOWN if not lose and not win: screen.blit(background, (0, 0)) # Draw wall for i in range(len(map)): for j in range(len(map[i])): if map[i][j] == 1: screen.blit( wallImage, (j * WALL_SIZE, i * WALL_SIZE)) screen.blit(playerImage, (x, y)) # Draw players for i in range(len(playersGrid)): for j in range(len(playersGrid[i])): if playersGrid[i][j] != 0: pygame.draw.rect( screen, colors[playersGrid[i][j] - 1], (i * PLAYER_SIZE, j * PLAYER_SIZE, PLAYER_SIZE, PLAYER_SIZE)) for i in range(len(players)): label = fontPlayerss.render(players[i], 1, colors[i]) screen.blit(label, (520, 20 + (i * 40))) if lose: wait = False label = myfont.render("Vous avez perdu !", 1, (255, 0, 0)) screen.blit(label, (100, 100)) labelScore = myfontScore.render( "Score : " + str(score), 2, (255, 255, 255)) screen.blit(labelScore, (115, 135)) pygame.display.flip() elif win: wait = False label = myfont.render("Vous avez gagne !", 1, (0, 255, 0)) screen.blit(label, (100, 100)) labelScore = myfontScore.render( "Score : " + str(score), 1, (255, 255, 255)) screen.blit(labelScore, (115, 135)) pygame.display.flip() pygame.display.flip() utils.send_data(utils.Global.sock_game, idEnemy) idEnemy = -1 utils.send_data(utils.Global.sock_game, lose) utils.send_data(utils.Global.sock_game, playersGrid) allKills = utils.recv_data(utils.Global.sock_game) for i in allKills: if i == id and not win and not lose: score = score + 100 allLost = utils.recv_data(utils.Global.sock_game) nbPlayer = len(allLost) nbLost = 0 for i in allLost: if i == True: nbLost = nbLost + 1 if nbLost == (nbPlayer - 1) and not lose and not win: win = True score = score + 300 playersGrid = utils.recv_data(utils.Global.sock_game) utils.send_data(utils.Global.sock_game, score) if wait: utils.send_data(utils.Global.sock_game, False) else: utils.send_data(utils.Global.sock_game, True) finish = utils.recv_data(utils.Global.sock_game) if finish: if win: label = myfont.render("Vous avez gagne !", 1, (0, 255, 0)) screen.blit(label, (100, 100)) labelScore = myfontScore.render( "Score : " + str(score), 1, (255, 255, 255)) screen.blit(labelScore, (115, 135)) pygame.display.flip() time.sleep(2) running = False son.stop() pygame.display.quit()
# Read the reply command utils.recv_data_into(sock, tmp_view[:5], 5) cmd = tmp_buf[:5].decode('ascii') if cmd != 'image': raise RuntimeError("Unexpected server reply") # Read the image buffer size utils.recv_data_into(sock, tmp_view, 7) img_size = int(tmp_buf.decode('ascii')) # Read the image buffer utils.recv_data_into(sock, img_view[:img_size], img_size) # Read the final handshake cmd = utils.recv_data(sock, 5).decode('ascii') if cmd != 'enod!': raise RuntimeError( "Unexpected server reply. Expected 'enod!', got '{}'".format( cmd)) # Transaction is done, we now process/display the received image img = jpeg_decode_func(img_view[:img_size]) cv2.imshow("Image", img) keep_running = not (cv2.waitKey(1) & 0xFF == ord('q')) if not keep_running: sock.sendall('quit!'.encode('ascii')) idx += 1 if idx == 30: t1 = time.time()