我有一个游戏,我正在使用一些网络来制作多人游戏。我创建了一个自定义模块(不是最好的),将两个值(XY)从-1048576转换为+1048576,将值从0到60(运行状况)转换为6个字符。因此,在6个字节中,我可以发送所有信息。
但这是在Python 2中工作,在Python 3中我发现我无法发送一个' str'与角色,所以我使用了' .encode()'在发送之前和' .decode()'在我的任何功能中使用它之前。但这似乎不起作用。
我不太确定。有什么帮助吗?
模块:
#IMPORT MODULES
from sys import version_info
#------------------------------------------------------------------------------
#FUNTIONS
#Binary String to Characters
def BinToMsg(text):
if version_info[0] <= 2: return "".join(chr(int(text[i:i+8], 2)) for i in range(0, len(text), 8))
else:
data = "".join(chr(int(text[i:i+8], 2)) for i in range(0, len(text), 8))
return data.encode()
#Characters to Binary String
def MsgToBin(text):
if version_info[0] <= 2: return "".join('{:08b}'.format(ord(c)) for c in text)
else:
text = text.decode()
return "".join('{:08b}'.format(ord(c)) for c in text)
#Corrects 0's values in Binary Strings
def fixDigit(text, digits):
lenth = digits - len(text)
for loop in range(lenth): text = "0" + text
return text
#Data to Characters
def DataToMsg(x,y,health):
if health >= 2**6 or health < 0: return None
bins = fixDigit(bin(health)[2:],6)
for cord in (x,y):
if cord >= 2**20: return None
if cord < 0: bins += "0"
else: bins += "1"
bins += fixDigit(bin(int(str(cord).replace("-","")))[2:],20)
return BinToMsg(bins)
#Characters to Data
def MsgToData(msg):
bins = MsgToBin(msg)
data = {"Health":int(bins[:6],2)}
data["X"] = int(bins[7:27],2)
data["Y"] = int(bins[28:48],2)
if bins[6] == "0": data["X"] *= -1
if bins[27] == "0": data["Y"] *= -1
return data
这会像这样使用......
Player = {"X":-1234,"Y":5678,"Health":23}
...
connection.send(DataToMsg(Player["X"],Player["Y"],Player["Health"]))
...
print(MsgToData(connection.recv(6))
...
Output: {"X":-1234,"Y":5678,"Health":23}
答案 0 :(得分:0)
当String以UTF-8(默认编码)编码时,长度会增加。因此,如果将connection.recv()设置为6,则不会收到所有信息。只是一些切碎。所以当你解码它时会给你一个错误。
为了保持相同的长度,我觉得将其编码为“cp037”非常有用。
用法
string.encode("cp037")
...
string.decode("cp037")