def __init__(self, config): # ゲーム内データの生成 self.config = config self.data = {} # ウィンドウオブジェクトを作成 self.window = tk.Tk() # 各インスタンスの生成 self.nc = NetworkClient() print(f'[DEBUG] selfData: {self.nc.selfdata}') tmp_player_id = self.nc.player_id if self.config['manual']: self.keyinput = KeyInput(self.window) else: # オートモード self.keyinput = AutoKeyInput(self.window, tmp_player_id, self.data) # Neworkコントローラで設定された初期値を渡す(*でタプル展開) self.cm = ClientModel(self.window, self.keyinput, *(self.nc.selfdata)) self.bm = BulletManager(self.window) self.init_data() # ビューの生成 self.view = View(self.window, self.data, self.cm.id, self.config) # 最初の1回(update内で再帰的にupdateが呼ばれてループとなる) # モデルとビューは更新頻度(TickRate, FPS)が異なるので別々に呼ぶ self.update_model() self.update_view() self.window.mainloop()
def main(username: str): pygame.init() # os.environ['SDL_VIDEO_CENTERED'] = '1' # make game window appears in the middle of the screen # # GAME_WINDOW = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) # pygame.display.set_caption("BattleShip Bastien") # pygame.display.set_icon(pygame.image.load("assets/images/warship.png")) client = NetworkClient(username) my_game = Game() print("This is your grid : ") print(my_game.my_grid) place_boats(my_game) print(client.send((MessageType.SEND_MY_GRID, my_game.my_grid))[1]) print("Waiting for your opponent...") startGame = False while not startGame: if client.receive_from_server()[0] == MessageType.START_PLAY: startGame = True print("Start game") while startGame: turn = client.send((MessageType.WHOSE_TURN, "")) if turn[0] == MessageType.END_GAME: break elif turn[0] == MessageType.WHOSE_TURN: if turn[1] == username: # my turn print("****YOUR TURN****") print_grids(my_game) while True: x = int(input("Enter x guess (0-9):")) if 0 <= x <= 9: break while True: y = int(input("Enter y guess (0-9):")) if 0 <= y <= 9: break my_game.attack_enemy((x, y)) my_game.my_guessed = client.send( (MessageType.SEND_MY_GUESSED, my_game.my_guessed))[1] else: # opponent's turn print("****OPPONENT TURN****") print_grids(my_game) print("OPPONENT IS PLAYING, PLEASE WAIT...") answer = client.send((MessageType.UPDATED_GRID, "")) if answer[0] == MessageType.UPDATED_GRID: my_game.my_grid = answer[1] print_grids(my_game) else: print("End game, thanks for playing.") break client.send((MessageType.DISCONNECT, )) pygame.quit() quit()
def __init__(self): self.type = "NetworkClientModule" # ||=======================|| # Program Classes self.networkClient = NetworkClient() self.controllerDataSync = ControllerDataSync(self.networkClient) self.communicationController = CommunicationController(self.type) # ||=======================|| configLoader = ConfigLoader() self.config = configLoader.getConfig(self.type) # ||=======================|| self.debugLogger = DebugLogger(self.type) self.debugLogger.setMessageSettings( ast.literal_eval(self.config["Debug"]), ast.literal_eval(self.config["Standard"]), ast.literal_eval(self.config["Warning"]), ast.literal_eval(self.config["Error"])) # ||=======================|| # Defaults self.pipes = {}
if CONSTANTS.USING_SENSOR_BOARD: LOGGER.Debug("Initializing sensor serial handler...") sensorSerialHandler = SerialHandler(CONSTANTS.SENSOR_BOARD_PORT) sensorSerialHandler.initSerial() val = "" val = sensorHandler.getSensorValues() LOGGER.Debug(val) if CONSTANTS.USING_MOTOR_BOARD: LOGGER.Debug("Initializing motor serial handler...") motorSerialHandler = SerialHandler(CONSTANTS.MOTOR_BOARD_PORT) motorSerialHandler.initSerial() if CONSTANTS.USING_NETWORK_COMM: networkClient = NetworkClient(CONSTANTS.CONTROL_STATION_IP, CONSTANTS.CONTROL_STATION_PORT) inboundMessageQueue = MessageQueue() networkClient.setInboundMessageQueue(inboundMessageQueue) outboundMessageQueue = MessageQueue() lastReceivedMessageNumber = -1 currentReceivedMessageNumber = -1 stateStartTime = -1 # initialize motors LOGGER.Debug("Initializing motor objects...") leftMotor = Motor("LeftMotor", 1, MOTOR_MODES.K_PERCENT_VBUS) rightMotor = Motor("RightMotor", 2, MOTOR_MODES.K_PERCENT_VBUS) #initialize sensors LOGGER.Debug("Initializing sensorobjects...")
def load_data(self): print "Loading object cache." start_time = time.time() with sqlite3.connect(self.db_file_name) as conn: cursor = conn.cursor() cursor.execute(Network.SQL_SELECT_ALL) allrows = cursor.fetchall() print "Loading networks. Found %i existing networks." % len(allrows) for row in allrows: network = Network.from_sqlite_data_row(row) self.networks[network.bssid] = network cursor.execute(NetworkEncryption.SQL_SELECT_ALL) allrows = cursor.fetchall() print "Loading network encryptions. Found %i existing network encryptions." % len(allrows) for row in allrows: network_encryption = NetworkEncryption.from_sqlite_data_row(row) network = self.networks[network_encryption.network_bssid] network.encryptions[network_encryption.encryption] = network_encryption cursor.execute(NetworkESSID.SQL_SELECT_ALL) allrows = cursor.fetchall() print "Loading network essids. Found %i existing network essids." % len(allrows) for row in allrows: network_essid = NetworkESSID.from_sqlite_data_row(row) network = self.networks[network_essid.network_bssid] network.essids[network_essid.essid] = network_essid cursor.execute(NetworkLocation.SQL_SELECT_ALL) allrows = cursor.fetchall() print "Loading network locations. Found %i existing network locations." % len(allrows) for row in allrows: network_location = NetworkLocation.from_sqlite_data_row(row) network = self.networks[network_location.network_bssid] network.locations.append(network_location) cursor.execute(Client.SQL_SELECT_ALL) allrows = cursor.fetchall() print "Loading clients. Found %i existing clients." % len(allrows) for row in allrows: client = Client.from_sqlite_data_row(row) self.clients[client.client_mac] = client cursor.execute(NetworkClient.SQL_SELECT_ALL) allrows = cursor.fetchall() print "Loading network clients. Found %i existing network clients." % len(allrows) for row in allrows: network_client = NetworkClient.from_sqlite_data_row(row) network = self.networks[network_client.network_bssid] network.clients[network_client.client_mac] = network_client client = self.clients[network_client.client_mac] client.network_clients[network_client.network_bssid] = network_client cursor.execute(ProbeRequest.SQL_SELECT_ALL) allrows = cursor.fetchall() print "Loading probe requests. Found %i existing probe requests." % len(allrows) for row in allrows: probe_request = ProbeRequest.from_sqlite_data_row(row) client = self.clients[probe_request.client_mac] client.probe_requests[probe_request.get_ssid_or_empty_string()] = probe_request cursor.execute(ClientLocation.SQL_SELECT_ALL) allrows = cursor.fetchall() print "Loading client locations. Found %i existing client locations." % len(allrows) for row in allrows: client_location = ClientLocation.from_sqlite_data_row(row) client = self.clients[client_location.client_mac] client.locations.append(client_location) cursor.execute(ImportedFile.SQL_SELECT_ALL) allrows = cursor.fetchall() print "Loading imported files. Found %i existing imported files." % len(allrows) for row in allrows: imported_file = ImportedFile.from_sqlite_data_row(row) self.imported_files[imported_file.file_name] = imported_file cursor.execute(ImportedHostnameFile.SQL_SELECT_ALL) allrows = cursor.fetchall() print "Loading imported hostname files. Found %i existing imported hostname files." % len(allrows) for row in allrows: imported_hostname_file = ImportedHostnameFile.from_sqlite_data_row(row) self.imported_hostname_files[imported_hostname_file.file_name] = imported_hostname_file end_time = time.time() processing_time = end_time - start_time print "Completed loading object cache in %s secs." % str(round(processing_time,2))
def parse_wireless_client_elements(self, network, wireless_client_elements, file_name): for wireless_client_element in wireless_client_elements: client_mac = wireless_client_element.find("client-mac").text network_client = network.clients.get(client_mac) if network_client == None: network_client = NetworkClient() network.clients[client_mac] = network_client network_client.is_dirty = True network_client.increment_number_of_times_seen() network_client.client_mac = client_mac network_client.network_bssid = network.bssid network_client.update_seen_first_time(self.get_date_from_kismet_string(wireless_client_element.get("first-time"))) network_client.update_seen_last_time(self.get_date_from_kismet_string(wireless_client_element.get("last-time"))) network_client_previous_total_packets = network_client.total_packets network_client_number_of_new_packets = int(wireless_client_element.find("packets").find("total").text) network_client.update_total_packets(network_client_number_of_new_packets) network_client_gps_info_element = wireless_client_element.find("gps-info") client = self.data_repository.get_or_create_client(client_mac) if network_client.network_bssid not in client.network_clients: client.network_clients[network_client.network_bssid] = network_client if not network_client_gps_info_element == None: network_client_avg_lat = float(network_client_gps_info_element.find("avg-lat").text) network_client_avg_lon = float(network_client_gps_info_element.find("avg-lon").text) network_client_location_seen_time = self.get_date_from_kismet_string(wireless_client_element.get("last-time")) network_client.update_gps(network_client_avg_lat, network_client_avg_lon, network_client_previous_total_packets, network_client_number_of_new_packets) client.locations.append(ClientLocation(0, client_mac, network_client_avg_lat, network_client_avg_lon, network_client_location_seen_time, file_name)) client.update_details_from_network_client(network_client)
class Controller: def __init__(self, config): # ゲーム内データの生成 self.config = config self.data = {} # ウィンドウオブジェクトを作成 self.window = tk.Tk() # 各インスタンスの生成 self.nc = NetworkClient() print(f'[DEBUG] selfData: {self.nc.selfdata}') tmp_player_id = self.nc.player_id if self.config['manual']: self.keyinput = KeyInput(self.window) else: # オートモード self.keyinput = AutoKeyInput(self.window, tmp_player_id, self.data) # Neworkコントローラで設定された初期値を渡す(*でタプル展開) self.cm = ClientModel(self.window, self.keyinput, *(self.nc.selfdata)) self.bm = BulletManager(self.window) self.init_data() # ビューの生成 self.view = View(self.window, self.data, self.cm.id, self.config) # 最初の1回(update内で再帰的にupdateが呼ばれてループとなる) # モデルとビューは更新頻度(TickRate, FPS)が異なるので別々に呼ぶ self.update_model() self.update_view() self.window.mainloop() def init_data(self): self.data[f'bullets{self.cm.id}'] = {} self.data[f'player{self.cm.id}'] = {} self.data[f'player{self.cm.id}']['id'] = self.cm.id self.data[f'player{self.cm.id}']['x'] = self.cm.x self.data[f'player{self.cm.id}']['y'] = self.cm.y self.data[f'player{self.cm.id}']['point'] = self.cm.point self.data[f'player{self.cm.id}']['state'] = self.cm.state self.data[f'player{self.cm.id}']['direction'] = self.cm.direction def create_packet(self): # プレイヤーと弾丸の情報をタプルにして送信する # タプルの構成を変更した場合,Serverの初期値設定の項目も変更すること sendData = {} sendData['player'] = (self.cm.id, self.cm.x, self.cm.y, self.cm.point, self.cm.state, self.cm.direction) sendData['bullets_id'] = self.cm.id sendData['bullets'] = [] for b in self.bm.bulletList: bullet = (b.x, b.y, b.v, b.direction) sendData['bullets'].append(bullet) return sendData def set_sendData(self, sendData): self.nc.send_data(sendData) def set_recievedlData(self, receiveData): gamedata = receiveData for i in range(20): # gamedataのキーにplayer{i}が存在しているなら if f'player{i}' in gamedata: player_data = gamedata[f'player{i}'] # 新規プレイヤーなら辞書を追加 if f'player{i}' not in self.data: self.data[f'player{i}'] = {} self.data[f'player{i}']['id'] = player_data[0] self.data[f'player{i}']['point'] = player_data[3] self.data[f'player{i}']['state'] = player_data[4] self.data[f'player{i}']['direction'] = player_data[5] # 自分の座標データはクライアントのものを用いるので更新しない(敵の情報だけ更新) if i != self.cm.id: self.data[f'player{i}']['x'] = player_data[1] self.data[f'player{i}']['y'] = player_data[2] self.data[f'player{i}']['direction'] = player_data[5] for i in range(20): # 弾丸も同様に設定 if f'bullets{i}' in gamedata and i != self.cm.id: # 一旦消して再設定する self.data[f'bullets{i}'] = [] for b in gamedata[f'bullets{i}']: bullet = { 'id': i, 'x': b[0], 'y': b[1], 'v': b[2], 'direction': b[3] } self.data[f'bullets{i}'].append(bullet) self.cm.point = self.data[f'player{self.cm.id}']['point'] def update_model(self): # アップデート順番は大事 self.keyinput.update() self.cm.update() self.bm.update() # モデルデータの更新 # ここで扱っているのは描画に必要な情報のみ # 内部モデルClientModel(cm)には触れない recieveData = self.nc.update().copy() #帰り値が辞書型なのでコピーをとっておく # ネットワークの下り遅延 ミリ秒指定 if self.config['downlinkdelay'] > 0: timer = Timer(self.config['downlinkdelay'] / 1000, self.set_recievedlData, (recieveData, )) timer.start() else: self.set_recievedlData(recieveData) # ネットワークの上り遅延 ミリ秒指定 sendData = self.create_packet() if self.config['uplinkdelay'] > 0: timer = Timer(self.config['uplinkdelay'] / 1000, self.set_sendData, (sendData, )) timer.start() else: self.set_sendData(sendData) ###### # 自プレイヤーの位置はと弾はクライアントのものを使って描画する #self.data[f'player{self.cm.id}'] = {} #self.data[f'player{self.cm.id}']['id'] = self.cm.id self.data[f'player{self.cm.id}']['x'] = self.cm.x self.data[f'player{self.cm.id}']['y'] = self.cm.y self.data[f'player{self.cm.id}']['direction'] = self.cm.direction #self.data[f'player{self.cm.id}']['point'] = self.cm.point #self.data[f'player{self.cm.id}']['state'] = self.cm.state # 弾も同様 self.data[f'bullets{self.cm.id}'] = [] for b in self.bm.bulletList: bullet = { 'id': self.cm.id, 'x': b.x, 'y': b.y, 'v': b.v, 'direction': b.direction } self.data[f'bullets{self.cm.id}'].append(bullet) # 1000/FPS ミリ秒間隔で再実行 self.window.after(int(1000 // FPS), self.update_model) def update_view(self): self.view.update() # 1000/FPS_VIEW ミリ秒間隔で再実行 self.window.after(int(1000 // VIEW_FPS), self.update_view)
from NetworkClient import NetworkClient from MessageQueue import MessageQueue import Constants as CONSTANTS from Constants import LOGGER CONTROL_STATION_IP = "130.215.122.163" networkClient = NetworkClient(CONTROL_STATION_IP, 11000) inboundMessageQueue = MessageQueue() networkClient.setInboundMessageQueue(inboundMessageQueue) outboundMessageQueue = MessageQueue() lastReceivedMessageNumber = -1 currentReceivedMessageNumber = -1 stateStartTime = -1 while True: if CONSTANTS.USING_NETWORK_COMM: connected = False while (not connected): try: if (outboundMessageQueue.isEmpty()): networkClient.send("Hiiiii\n\r") else: networkClient.send(outboundMessageQueue.getNext()) LOGGER.Debug("Connected to socket") connected = True except Exception as e: # print e LOGGER.Debug( "Could not connect to network, attempting to reconnect...")
motorHandler = MotorHandler() sensorHandler = SensorHandler() if CONSTANTS.USING_SENSOR_BOARD: LOGGER.Debug("Initializing sensor serial handler...") sensorSerialHandler = SerialHandler(CONSTANTS.SENSOR_BOARD_PORT) sensorSerialHandler.initSerial() if CONSTANTS.USING_MOTOR_BOARD: LOGGER.Debug("Initializing motor serial handler...") motorSerialHandler = SerialHandler(CONSTANTS.MOTOR_BOARD_PORT) motorSerialHandler.initSerial() #initialize network comms & server thread if CONSTANTS.USING_NETWORK_COMM: networkClient = NetworkClient(CONSTANTS.CONTROL_STATION_IP, CONSTANTS.CONTROL_STATION_PORT) inboundMessageQueue = MessageQueue() networkClient.setInboundMessageQueue(inboundMessageQueue) outboundMessageQueue = MessageQueue() lastReceivedMessageNumber = -1 currentReceivedMessageNumber = -1 stateStartTime = -1 # setup some variables that will be used with each iteration of the loop #currentMessage = NetworkMessage("") # initialize motors LOGGER.Debug("Initializing motor objects...") leftDriveMotor = Motor("LeftDriveMotor", CONSTANTS.LEFT_DRIVE_DEVICE_ID, MOTOR_MODES.K_PERCENT_VBUS) rightDriveMotor = Motor("RightDriveMotor", CONSTANTS.RIGHT_DRIVE_DEVICE_ID,
def __init__(self, root, ip, port): self.networkClient = NetworkClient(ip, port) self.root = root self.screenWidth = self.root.winfo_screenwidth() self.screenHeight = self.root.winfo_screenheight()