Vizard 7 » Tutorials & Examples » Networking » Text messaging
7.6

Tutorial: Text messaging

Now let's add some code to allow our robots to text message each other.

 

First, add text fields for incoming and outgoing messages.

inbox = viz.addText('',parent=viz.SCREEN,pos=(0.1,0.8,0))
outbox = viz.addText('',parent=viz.SCREEN,pos=(0.1,0.1,0))

Next, create a new variable, draft_text, which will be the message that you send to the other computer.

#Create a variable for the draft of the outgoing message.
draft_text = ' '

Add the following keyboard function to accept keyboard input. Each time a key is pressed the value of draft_text gets updated. When the character return is hit, the message gets sent.

def mykeyboard(key):
    global draft_text
    #If the length of the key is 1 then
    #add the character to the string.
    if len(key) == 1:
        draft_text += key
    #If the key is a character return, end the line, make the
    #outgoing message equal to the draft message, and set the draft equal
    # to a blank space.
    elif key == viz.KEY_RETURN:
        target_mailbox.send(action=updateMessage, message=draft_text)
        draft_text = ' '
    #If the key is the backspace key then remove the last character of the string.
    elif key == viz.KEY_BACKSPACE:
        draft_text = draft_text[:-1]
    #Update the input text field so that you can see what you're typing.
    outbox.message(draft_text)

#Add a callback for that keyboard event.
viz.callback(viz.KEYDOWN_EVENT,mykeyboard)

The onNetwork function is already set up to receive the message data but we need a function to process it. Go back and insert the highlighted code into your script to update the screen text:

def updatePlayer(e):
    player_matrix.setPosition(e.pos)
    player_matrix.setQuat(e.quat)

def updateMessage(e):
    inbox.message(e.message)

# Listens for any incomming messages
def onNetwork(e):
    if e.sender.upper() == target_machine:
        e.action(e)

The updateMessage function will get called whenever the action attribute in the event data is set to 'updateMessage'.

 

Now start up the worlds on both computers and try chatting as you chase each other around the maze.

Networking computers

Text messaging