import pygame, select from socket import * def initialize_constants(): """ This function sets some global constants (i.e., the values of these global variables never change). """ global name name = raw_input("Please type in your name: ") pygame.init() # set up the display window global width, height, screen width = 800 height = 600 screen = pygame.display.set_mode((width,height)) # load the ballon picture global balloon balloon = pygame.image.load("red_balloon.gif") balloon = balloon.convert() global balloon2 balloon2 = pygame.image.load("green_balloon.gif") balloon2 = balloon2.convert() # load sound global pop_sound pop_sound = pygame.mixer.Sound("pop.wav") # load font global myFont myFont = pygame.font.Font(None,30) # set up socket global UDP_sock, buf buf = 1024 UDP_sock = socket(AF_INET,SOCK_DGRAM) global server_addr server_host = "localhost" server_port = 3001 server_addr = (server_host, server_port) UDP_sock.sendto("connect "+name, server_addr) def run_game(): # initialize the balloons' positions and speeds b_x = 100 b_y = 100 b2_x = 300 b2_y = 300 # initialize the score score = 0 scorelist = [] dead = False keepGoing = True while (keepGoing): ### handle events for event in pygame.event.get(): if event.type == pygame.QUIT: keepGoing = False # If the player clicks, a message containing the # coordinates of the clicks is sent to the server, which # should return a message including the new score for this # player elif event.type == pygame.MOUSEBUTTONDOWN: mouse_x, mouse_y = pygame.mouse.get_pos() msg = "click "+str(mouse_x)+" "+str(mouse_y) UDP_sock.sendto(msg, server_addr) ### handle messages from the server [in_msgs, out, err] = select.select([UDP_sock], [], [], 0) if len(in_msgs) > 0: received_string, sender = UDP_sock.recvfrom(buf) received_string = received_string.strip() received_list = received_string.split(" ") if received_list[0] == "position": b_x = received_list[1] b_y = received_list[2] b2_x = received_list[3] b2_y = received_list[4] elif received_list[0] == "hit": pop_sound.play() score = received_list[1] elif received_list[0] == "scores": scorelist = received_list[1:] ### draw everything screen.fill(pygame.color.Color("darkblue")) # score x = 10 y = 10 label = myFont.render("Your score: "+str(score), True, pygame.color.Color("magenta")) screen.blit(label, (x,y)) for idx in range(1,len(scorelist),2): y = y + 30 label = myFont.render(scorelist[idx-1]+" "+scorelist[idx], True, pygame.color.Color("magenta")) screen.blit(label, (x,y)) # balloon images screen.blit(balloon,(int(b_x), int(b_y))) screen.blit(balloon2,(int(b2_x), int(b2_y))) pygame.display.update() def done(): global myFont myFont = None UDP_sock.sendto("disconnect", server_addr) UDP_sock.close() pygame.quit() def main(): initialize_constants() run_game() done() main()