首页 > 解决方案 > Python代码在没有打印功能的情况下无法工作

问题描述

我已经使用 python 套接字制作了一个服务器和客户端。服务器接受所有客户端并将每个客户端发送到一个新线程。每个线程给客户端一个名称(1 到 100 之间的随机整数),然后在字典中设置它们的值。

该线程将字典发送到客户端,以便它可以在 Pygame 窗口上呈现所有内容。客户端根据其玩家位置编辑值,并将编辑后的字典发送回线程,线程将值添加到服务器字典。

服务器字典由所有客户端共享。

我的问题是,我正在使用“全局”python 关键字,除非我打印它,否则它似乎不起作用。客户正在接收价值,但对他们来说,只有他们的立场在改变。通过打印功能,客户可以得到每个人的位置。

发生了什么事,无论如何在没有打印功能的情况下这样做吗?

服务器.py:

import socket
import threading
import json
import random
import time

# Set Up
HOST = "localhost"
PORT = 9999
s = socket.socket()
s.bind((HOST, PORT))

print("The server has started and is ready to accept participants!")

# random int: location as list
all_locs = {1: [200, 200], 2: [700, 500]}

def recv_and_send(c, addr):
    random_val = str(random.randrange(1, 101))
    c.send(str(random_val).encode())
    print(f"Yayyy! We have gotten a new connection at {addr} and they have been given a value ({random_val})!")
    c.recv(0)

    while True:
        global all_locs
        
        print(all_locs) # this one
        
        c.send(json.dumps(all_locs).encode())
        received = json.loads(c.recv(2048).decode())
        all_locs = received

s.listen()
while True:
    c, addr = s.accept()
    print(f"A new connection ({addr}) has just been accepted!")
    t = threading.Thread(target=recv_and_send, args=(c, addr,))
    t.start()

客户端.py

import json
import socket
import json
import pygame
import random

# setting up pygame
pygame.init()
win = pygame.display.set_mode((800, 600))

# setting up sockets
HOST = "localhost"
PORT = 9999
s = socket.socket()
s.connect((HOST, PORT))

print("We have been accepted!")

pos = [random.randrange(100, 700), random.randrange(100, 500)]

random_val = s.recv(2048).decode().split("{")[0]
print(f"Our value is {random_val}!")
s.send(b"")

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    win.fill((0, 0, 0))
    
    keys = pygame.key.get_pressed()

    if keys[pygame.K_w]:
        pos[1] -= 0.2
    elif keys[pygame.K_s]:
        pos[1] += 0.2
    if keys[pygame.K_a]:
        pos[0] -= 0.2
    elif keys[pygame.K_d]:
        pos[0] += 0.2
    pos = [int(p) for p in pos]


    # get the data
    received_data = s.recv(2048)
    received_data = received_data.decode()
    recv_all_locs = json.loads(received_data)

    # change the data
    recv_all_locs[random_val] = pos

    # show the data
    if len(recv_all_locs) > 0:
        for val in recv_all_locs.values():
            pygame.draw.rect(win, (255, 0, 0), (val[0], val[1], 10, 10))
    pygame.display.update()

    #if len(recv_all_locs) == 4:
    #    print(recv_all_locs)

    # send the data
    s.send(json.dumps(recv_all_locs).encode())

pygame.quit()
s.close()

标签: pythonpython-3.xsocketspygame

解决方案


推荐阅读