Задать вопрос
@i3stone

Как добавить цикл в сервер-клиентное приложение python kivy?

Здравствуйте! Есть онлайн игра, точнее онлайн в процессе, я хочу серверу отправлять координаты нашего игрока, но это надо делать непрерывно-постоянно, но если я в Kivy-приложение добавляю цикл в котором отправка данных, то игра зависает, как сделать так что бы клиент постоянно отсылал данные серверу и наоборот?

код-сервер

# install_twisted_rector must be called before importing and using the reactor
from kivy.support import install_twisted_reactor

install_twisted_reactor()

from twisted.internet import reactor
from twisted.internet import protocol


class EchoServer(protocol.Protocol):
    def dataReceived(self, data):
        response = self.factory.app.handle_message(data)
        if response:
            self.transport.write(response)


class EchoServerFactory(protocol.Factory):
    protocol = EchoServer

    def __init__(self, app):
        self.app = app


from kivy.app import App
from kivy.uix.label import Label
from kivy.core.window import Window
WindowWidth = 500
WindowHeight = 500


Window.clearcolor = (.2, .2, .2, 1)
Window.size = (WindowWidth, WindowHeight)


class TwistedServerApp(App):
    label = None
    connection = None
    textbox = None
    

    def build(self):
        self.label = Label(text="server started\n")
        reactor.listenTCP(8000, EchoServerFactory(self))
        return self.label

    def handle_message(self, msg):
        msg = msg.decode('utf-8')
        print(msg)
        self.label.text = "received:  {}\n".format(msg)

        # что бы выводило всю информацию получаемую от клиента
        if msg != "43213518243":
            print(msg)
            # отправка
            msg = "СЕРВЕР ПОЛУЧИЛ КООРДИНАТЫ"

        if msg == "test":
            msg = "0_0"
            
        if msg == "plop":
            msg = "Kivy Rocks!!!"
        self.label.text += "responded: {}\n".format(msg)
        return msg.encode('utf-8')

    

if __name__ == '__main__':
    TwistedServerApp().run()



# self.connection.write(msg.encode('utf-8'))



код-клиент

# install_twisted_rector must be called before importing the reactor
from __future__ import unicode_literals

from kivy.support import install_twisted_reactor

install_twisted_reactor()

# A Simple Client that send messages to the Echo Server
from twisted.internet import reactor, protocol


class EchoClient(protocol.Protocol):
    def connectionMade(self):
        self.factory.app.on_connection(self.transport)

    def dataReceived(self, data):
        self.factory.app.print_message(data.decode('utf-8'))


class EchoClientFactory(protocol.ClientFactory):
    protocol = EchoClient

    def __init__(self, app):
        self.app = app

    def startedConnecting(self, connector):
        self.app.print_message('Started to connect.')

    def clientConnectionLost(self, connector, reason):
        self.app.print_message('Lost connection.')

    def clientConnectionFailed(self, connector, reason):
        self.app.print_message('Connection failed.')


from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.widget import Widget
from kivy.uix.image import Image
from kivy.core.window import Window
WindowWidth = 500
WindowHeight = 500


Window.clearcolor = (.2, .2, .2, 1)
Window.size = (WindowWidth, WindowHeight)












class WallImage(Image):

    def __init__(self, **kwargs):
        super(WallImage, self).__init__(**kwargs)
        self._keyboard = Window.request_keyboard(None, self)
        if not self._keyboard:
            return
        self._keyboard.bind(on_key_down=self.on_keyboard_down)
    # ??? ?????, ????? ??. ?????
    def on_keyboard_down(self, keyboard, keycode, text, modifiers):
        if keycode[1] == 'a':
            self.x -= 10
        elif keycode[1] == 'd':
            self.x += 10
        elif keycode[1] == 'w':
            self.y += 10
        elif keycode[1] == 's':
            self.y -= 10
        else:
            return False
        return True


wall = WallImage(source='wall.png', pos=(100, 100))

# it is PLAYER
class MoveableImage(Image):

    def __init__(self, **kwargs):
        super(MoveableImage, self).__init__(**kwargs)
        self._keyboard = Window.request_keyboard(None, self)
        if not self._keyboard:
            return
        self._keyboard.bind(on_key_down=self.on_keyboard_down)

    # ??????????????????.
    # ?????? ?????
    def collider(self):
        # collider size - (48, 48)
        # коллизия со стеной
        if self.x <= wall.x + 48 and self.x >= wall.x - 48 and self.y <= wall.y + 48 and self.y >= wall.y - 48:
            print("Collision!")
        else:
            print("....................")
            
    # управление
    def on_keyboard_down(self, keyboard, keycode, text, modifiers):
        if keycode[1] == 'left':
            self.x -= 10
            self.collider()
            
        elif keycode[1] == 'right':
            self.x += 10
            self.collider()
            
        elif keycode[1] == 'up':
            self.y += 10
            self.collider()
            
        elif keycode[1] == 'down':
            self.y -= 10
            self.collider()
            
        else:
            return False

        return True










wimg = MoveableImage(source='player.png', pos=(200, 200))









# A simple kivy App, with a textbox to enter messages, and
# a large label to display all the messages received from
# the server
class OnlineGameAndroidApp(App):
    connection = None
    textbox = None
    label = None

    def build(self):
        root = self.setup_gui()
        self.connect_to_server()
        
        return root

    def setup_gui(self):
        self.textbox = TextInput(size_hint_y=.1, multiline=False)
        self.textbox.bind(on_text_validate=self.send_message)
        self.label = Label(text='connecting...\n')
        layout = BoxLayout(orientation='vertical')
        layout.add_widget(self.label)
        layout.add_widget(self.textbox)
        layout.add_widget(wall)
        layout.add_widget(wimg)
        return layout

    def connect_to_server(self):
        reactor.connectTCP('localhost', 8000, EchoClientFactory(self))

    def on_connection(self, connection):
        self.print_message("Connected successfully!")
        self.connection = connection

    # отправка сообщения
    def send_message(self, *args):

        msg = str([wimg.x, wimg.y])#self.textbox.text
        if msg and self.connection:
            self.connection.write(msg.encode('utf-8'))
            #self.textbox.text = ""

    # получение сообщения
    def print_message(self, msg):
        self.label.text += "{}\n".format(msg)
        print(format(msg))


if __name__ == '__main__':
    OnlineGameAndroidApp().run()



а так же файлы:

player.png
6269177de3566641592132.png

wall.png
626917986c929703527255.png

  • Вопрос задан
  • 93 просмотра
Подписаться 1 Средний Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы