如何清除套接字缓冲区?

时间:2021-01-03 23:26:15

标签: python arrays json sockets

所以,我试图编写一个 python 版本的乒乓球游戏,球飞过监视器,当我试图用 json 模块将球线发送到服务器时,我遇到了额外的数据错误。所以我发现插座上塞满了球线,因为它没有删除旧的。我如何删除它们?

这是乒乓球的右侧部分,左侧部分相同但方向相反

# Ping-Pong game with turtle module.
# Done by Sri Manikanta Palakollu.
# Version - 3.7.0

import turtle as t
import json
import socket

ball_xy = [0, 0]


win = t.Screen()    # creating a window
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("someip", 10082))
win.title("Ping-Pong Game") # Giving name to the game.
win.bgcolor('black')    # providing color to the HomeScreen
win.setup(width=1920, height=1080) # Size of the game panel
win.tracer(0)   # which speed up's the game.

# Creating a right paddle for the game

paddle_right = t.Turtle()
paddle_right.speed(0)
paddle_right.shape('square')
paddle_right.shapesize(stretch_wid=5,stretch_len=1)
paddle_right.color('red')
paddle_right.penup()
paddle_right.goto(900, 0)

# Creating a pong ball for the game

ball = t.Turtle()
ball.speed(0)
ball.shape('circle')
ball.color('yellow')
ball.penup()
ball.goto(0, 0)
ball_dx = 0.1   # Setting up the pixels for the ball movement.
ball_dy = 0.1



def paddle_right_up():
 y = paddle_right.ycor()
 y = y + 15
 paddle_right.sety(y)

# Moving right paddle down

def paddle_right_down():
 y = paddle_right.ycor()
 y = y - 15
 paddle_right.sety(y)


win.onkeypress(paddle_right_up,"Up")
win.onkeypress(paddle_right_down,"Down")




# Main Game Loop

while True:
 win.update() # This methods is mandatory to run any game

 # Moving the ball
 ball.setx(ball.xcor() + ball_dx)
 ball.sety(ball.ycor() + ball_dy)

 # setting up the border

 if ball.ycor() > 540:   # Right top paddle Border
     ball.sety(540)
     ball_dy = ball_dy * -1


 if ball.ycor() < -540:  # Left top paddle Border
     ball.sety(-540)
     ball_dy = ball_dy * -1


 if ball.xcor() > 960:   # right width paddle Border
     player_a_score = player_a_score + 1
     ball.setx(960)
     ball_dx = ball_dx * -1


 # Handling the collisions with paddles.

 if(ball.xcor() > 890) and (ball.xcor() < 900) and (ball.ycor() < paddle_right.ycor() + 40 and ball.ycor() > paddle_right.ycor() - 40):
     ball.setx(890)
     ball_dx = ball_dx * -1

 ball_xy = [ball.xcor(), ball.ycor()]
 ready_data = json.dumps(ball_xy)
 s.sendall(ready_data.encode())

这是服务器部分

import socket
import json
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('someip', 10082))
s.listen(100)
conn, addr = s.accept()
print("connected:", addr)
while True:
 data = conn.recvmsg(1024)
 rdata = json.loads(data[0].decode())
 print(rdata)

0 个答案:

没有答案