弹幕
"""写一个弹幕"""
import pygame
import socket
from threading import Thread
from random import randint
message_list = []
# 输入子进程
class CoversationThread(Thread):
def __init__(self, conversation):
super().__init__()
self.conversation = conversation
def run(self):
while True:
message = self.conversation.recv(1024).decode(encoding='utf-8')
message_dict = {'content': message, 'x': 580, 'y': randint(20, 200), 'x_speed': -4}
message_list.append(message_dict)
print(message_list)
if __name__ == '__main__':
pygame.init()
screen = pygame.display.set_mode((600, 400))
screen.fill((254, 254, 254))
pygame.display.set_caption('屏幕')
pygame.display.flip()
server = socket.socket()
server.bind(('10.7.181.81', 8080))
server.listen(64)
while True:
conversation, address = server.accept()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
pygame.time.delay(50)
screen.fill((254, 254, 254))
if message_list:
for message in message_list[:]:
content = str(message['content'])
x = message['x']
y = message['y']
x_speed = message['x_speed']
if x + x_speed <= -10:
message_list.remove(message)
else:
message['x'] = x + x_speed
font = pygame.font.SysFont('Times', 20)
surface = font.render(content, True, (254, 0, 0))
screen.blit(surface, (x, y))
pygame.display.update()
c1 = CoversationThread(conversation)
c1.start()