1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# Filename: A08_multiplayer_demo_client.py
# Author: James D. Miller; Gustavus Adolphus College.

import sys, os
import pygame

# PyGame Constants
from pygame.locals import *
from pygame.color import THECOLORS

# Network stuff. Note "connection" is a single instantiation.
from PodSixNet.Connection import connection, ConnectionListener

# Argument parsing...
import argparse

#=======================================================================
# Classes       
#=======================================================================

class NetworkListener(ConnectionListener):
    def __init__(self, (host, port)):
        self.Connect((host, port))

        self.client_colors = {'C1': THECOLORS["green"],  'C2': THECOLORS["tan"],'C3': THECOLORS["black"],'C4': THECOLORS["blue"],
                              'C5': THECOLORS["pink"],   'C6': THECOLORS["red"],'C7': THECOLORS["coral"],'C8': THECOLORS["orangered1"],
                              'C9': THECOLORS["grey80"],'C10': THECOLORS["rosybrown3"]}
        
        self.background_color = THECOLORS["white"]
        self.client_name = 'C0'
        self.client_color = THECOLORS["black"]
        
    def Network_hello(self, data):
        global Player_ID, user_state
        print "Network_hello:", data
        
        Player_ID = data['P_ID']
        self.client_name = 'C' + str(Player_ID)
        
        self.background_color = THECOLORS["yellow"]
        self.client_color = self.client_colors[self.client_name]
        
        # Initialize user state dictionary.
        user_state = {'action': 'CN',
                      'ID': Player_ID,
                      'mouseXY':(0,0), 'mouseB1':'U',
                      'a':'U', 's':'U',
                      'd':'U', 'w':'U'}
        
        pygame.display.set_caption("Client: GamePad #" + str(Player_ID)) 
        
        
#=======================================================================
# Functions       
#=======================================================================

def signoff(user_state):
    sys.exit()
    
def checkforUserInput(user_state):
    
    # Check the button status.
    (button1, button2, button3) = pygame.mouse.get_pressed()    
    
    # Get all the events since the last call to get().
    for event in pygame.event.get():
        if (event.type == pygame.QUIT): 
            signoff(user_state)
        elif (event.type == pygame.KEYDOWN):
            if (event.key == K_ESCAPE):
                signoff(user_state)
            
            elif (event.key==K_c):
                client_display.fill(THECOLORS["blue"])  
            
            elif (event.key==K_1):            
                return 1           
            elif (event.key==K_2):                          
                return 2
            elif (event.key==K_3):
                return 3   
            
            elif (event.key==K_a):
                user_state['a'] = 'D'
            elif (event.key==K_s):
                user_state['s'] = 'D'
            elif (event.key==K_d):
                user_state['d'] = 'D'
            elif (event.key==K_w):
                user_state['w'] = 'D'
                
        elif (event.type == pygame.KEYUP):
            if (event.key==K_a):
                user_state['a'] = 'U'
            elif (event.key==K_s):
                user_state['s'] = 'U'
            elif (event.key==K_d):
                user_state['d'] = 'U'
            elif (event.key==K_w):
                user_state['w'] = 'U'
        
        elif event.type == pygame.MOUSEBUTTONDOWN:
            user_state['mouseB1'] = 'D'
        
        elif event.type == pygame.MOUSEBUTTONUP:
            user_state['mouseB1'] = 'U'

        # cursor x,y
        user_state['mouseXY'] = pygame.mouse.get_pos()

#=======================================================================
# Main program statements       
#=======================================================================

pygame.init()

client_display = pygame.display.set_mode((600,400))

# Instantiate clock to help control the framerate.
client_clock = pygame.time.Clock()

# Background color of the game pad.   
client_display.fill(THECOLORS["grey"])

# Font object for rendering text onto display surface.
fnt = pygame.font.SysFont("Arial", 14)

Player_ID = 0

parser = argparse.ArgumentParser(description='Input client parameters.')
# Example IP address used here; edit this line.
parser.add_argument('serverIP', type=str, nargs='?', default="138.236.65.69")
args = parser.parse_args()
print "args:", args.serverIP

# Initialize the state dictionary
user_state = {}

# Note, the connection can take place in the NetworkListener or here.
# This "connection" is an instatiation of the EndPoint class that is done in the Connection.py file.
# Note, if you do this here, you have to call the "DoConnect" method, not the "Connect" method that 
# is indicated on the web site.
#connection.DoConnect((args.serverIP, 4330))

network_listener = NetworkListener((args.serverIP, 4330))

framerate_limit = 100
flip_timer = 0.0

while True:
    
    dt_s = float(client_clock.tick(framerate_limit) * 1e-3)
    #client_clock.tick(framerate_limit)
    
    connection.Pump()
    network_listener.Pump()    
    
    checkforUserInput(user_state)
    if Player_ID != 0:
        #print "user_state", user_state
        connection.Send(user_state)
    
    flip_timer += dt_s
    if (flip_timer > 0.2):
        # Background
        client_display.fill( network_listener.background_color)
        
        # Small rectangle to illustrate the client color that will appear on the server screen.
        pygame.draw.rect(client_display, network_listener.client_color, pygame.Rect(50, 50, 60, 20), 3)
        
        # Small background rectangle for text
        pygame.draw.rect(client_display, THECOLORS["black"], pygame.Rect(150, 50, 35, 20))
        # Text to be displayed
        fps_string = "%.0f" % client_clock.get_fps()
        txt_surface = fnt.render(fps_string, True, THECOLORS["white"])
        client_display.blit(txt_surface, [158, 51])
    
        pygame.display.flip()
        flip_timer = 0.0