美文网首页
基于pygame的弹幕聊天程序

基于pygame的弹幕聊天程序

作者: pubalabala | 来源:发表于2019-05-30 15:57 被阅读0次

环境准备

安装pygame: pip install pygame
字体文件: aa.ttf

服务端代码

"""__author__ == Jefferson"""
from threading import Thread
import socket

threads = {}

class RecvThread(Thread):
    def __init__(self,conversation):
        super().__init__()
        self.message = ''
        self.conversation = conversation

    def run(self):
        while True:
            # 接收消息
            mesasge_data = self.conversation.recv(1024)
            print(mesasge_data.decode(encoding='utf-8'))
            RecvThread.send_all(mesasge_data.decode(encoding='utf-8'))

    @staticmethod
    def send_all(message):
        print(threads)
        for key in threads:
            threads[key].new_message = message
            print(threads[key])


class ServerThread(Thread):

    def __init__(self, conversation:socket, adress):
        super().__init__()
        self.conversation = conversation
        self.adress = adress
        self.old_message = ''
        self.new_message = ''


    def run(self):
        # 让客户端和服务器一直处于连接的状态
        t = RecvThread(self.conversation)
        t.start()
        while True:
            # 发消息
            if self.new_message != self.old_message:
                print(self.adress, self.new_message)
                self.conversation.send(self.new_message.encode())
                self.old_message = self.new_message



    def __str__(self):
        return 'conversation:'+str(self.conversation)+'address:'+str(self.adress)+'old_message:'+self.old_message+'new_message:'+self.new_message



if __name__ == '__main__':
    server = socket.socket()
    server.bind(('127.0.0.1', 8080))
    server.listen(50)

    while True:
        conversation, address = server.accept()
        print(address)
        if threads.get(address) == None:
            threads[address] = ServerThread(conversation, address)
            threads[address].start()
客户端代码
"""__author__ == Jefferson"""
import socket
import pygame
from random import randint
from threading import Thread


size_x = 900
size_y = 600
global message
messages = []


class Bullet():

    def __init__(self, name):
        self.position = (0,0)
        self.color = (randint(0,255),randint(0,255),randint(0,255))
        self.speed = -1
        self.font = ('./font/aa.ttf',40)
        self.text = ''
        self.name = name

    @classmethod
    def analyze(cls, revmsg):
        message = messages
        data = cls('temp')
        for key in revmsg:
            data.__setattr__(key,revmsg[key])
        message.append(data)



class ClientThread(Thread):
    '''客户端接收消息'''
    def __init__(self, client):
        super().__init__()
        self.client = client

    def run(self):
        while True:
            Bullet.analyze(eval(self.client.recv(1024).decode(encoding='utf-8')))

class DrawThread(Thread):
    '''窗口线程'''
    def __init__(self):
        super().__init__()

    def run(self):
        pygame.init()
        screen = pygame.display.set_mode((size_x, size_y))
        screen.fill((255, 255, 255))
        pygame.display.flip()
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    exit()
            DrawThread.draw(screen)
            DrawThread.move()
            pygame.display.flip()

    @staticmethod
    def draw(screen):
        message = messages
        screen.fill((255, 255, 255))
        if len(message) != 0:
            for item in message:
                font = pygame.font.Font(item.font[0], item.font[1])
                surface = font.render(item.name+': '+item.text, True, item.color)
                screen.blit(surface,item.position)

    @staticmethod
    def move():
        message = messages
        if len(message) != 0:
            for item in message:
                item.position = (item.position[0]+item.speed,item.position[1])
            i = 0
            while i < len(message):
                if message[i].position[0]+500 <= 0:
                    del message[i]
                    i -= 1
                i += 1



if __name__ == '__main__':
    drawThead = DrawThread()
    drawThead.start()
    name = input('你的名字:')
    bullet = Bullet(name)
    client = socket.socket()
    client.connect(('127.0.0.1', 8080))
    while True:
        # 收消息
        clientRecv = ClientThread(client)
        clientRecv.start()
        text = input('>>>')
        position = (size_x,randint(0,size_y-100))
        bullet.position = position
        bullet.text = text
        bullet.speed = randint(-3, -1)
        message = {'name': bullet.name,'text':bullet.text,'position':bullet.position,'color':bullet.color,'speed':bullet.speed,'font':bullet.font}
        client.send(str(message).encode())
实例代码地址

源码:

相关文章

网友评论

      本文标题:基于pygame的弹幕聊天程序

      本文链接:https://www.haomeiwen.com/subject/gtjvtctx.html