简体   繁体   English

将Pygame与python套接字配合使用,黑屏

[英]Using Pygame with python sockets, black screen

I have been trying to create a two player game in pygame. 我一直试图在pygame中创建一个两人游戏。 I did some research on sockets and have been trying to put them into the game. 我对套接字做了一些研究,并一直试图将它们放入游戏中。 This is my setup sockets function in the server, I won't put all the game code in since its quite long: 这是服务器中的我的设置套接字函数,由于它的时间很长,所以我不会放入所有游戏代码:

def create_sockets(self):
        self.ip = "192.168.1.68"
        self.port = 8888
        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server_socket.bind((self.ip, self.port))
        self.server_socket.listen(5)
        self.conn, self.addr = self.server_socket.accept()

But through trial and error, when server_socket.accept() is run, I get a black screen and a color wheel (I'm on a mac). 但是通过反复试验,运行server_socket.accept()时,我得到了黑屏和色轮(我在Mac上)。 Why is this happening? 为什么会这样呢? the same code works fine in my server test from before. 同样的代码在以前的服务器测试中也能正常工作。 Since I am very new to sockets please correct me on any mistakes/bad practice 由于我是套接字的新手,请纠正我的任何错误/不良做法

Thanks in advance 提前致谢

+1 to svk. +1即可。 Whenever I use Socket in pygame, I use threading to make it asynchronous. 每当我在pygame中使用Socket时,我都会使用线程化使其异步。 I'm pretty sure both .listen() and .accept() will freeze your program in a loop as those methods are waiting for something to happen. 我很确定.listen()和.accept()都会在程序中冻结这些程序,因为这些方法正在等待某些事情发生。

Here is the full code for a pong clone in pygame. 这是pygame中pong克隆的完整代码。 This is a "dumb" server, meaning it is not handling game logic, just sharing data with clients. 这是一个“哑”服务器,这意味着它不处理游戏逻辑,仅与客户端共享数据。

This may not be your preferred approach as a whole, but it does show how to handle asynchronous connection/listening. 从整体上看,这可能不是您的首选方法,但是它确实显示了如何处理异步连接/侦听。 As well as using pickle to encode/decode whatever data type you want. 以及使用pickle编码/解码所需的任何数据类型。 That way you can kick lists around and stuff. 这样一来,您就可以添加清单和其他内容。

# Server example:
from threading import Thread
import socket, pickle, logging

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("0.0.0.0", 12354))

logging.basicConfig(format='%(asctime)s:%(levelname)s:%(lineno)s %(message)s', level=logging.DEBUG)                                                                 
client_list = []
max_clients = 2 
global started  
started = 0                                                                                                                                                         

class Client():
    def __init__(self, conn = ''):

        self.conn = conn
        # add to global clients list
        client_list.append(self)                             
        self.client_thread = Thread(target = self.process_messages)
        self.client_thread.start()


    def process_messages(self):                                                                                                                                     
        while True:
            try:
                data = self.conn.recv(1024)
                # send to all in client_list except self                                     
                data = pickle.loads(data)                                                                                                                               
                data.append(started)                                                                                                                                    
                logging.info("Sending Data: {0}".format(data))
                data = pickle.dumps(data)
                for client in client_list:
                    if client != self:                                                                                                                                 
                        client.conn.sendall(data)                                                                                                                           
                data = ""
            except ConnectionResetError:
                logging.debug("Client Disconnected")
                break


def connection_manager():
    while len(client_list) < max_clients:
        logging.info('Listening for connections...')
        s.listen(1)
        conn, addr = s.accept()
        logging.info("Client connected: {0}".format(addr))
        x = Client(conn)
        logging.debug(client_list)
    logging.warning("Max clients reached")
    logging.info("No longer listening..")
    started = 0

accept_connections_thread = Thread(target = connection_manager)
accept_connections_thread.start()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM