#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- import socket, json, time import pygame # ---------- SOCKETS ---------- RESP_BUFFER_LENGTH = 1024 ip_adress="192.168.1.14" port=8080 LARGEUR_BLOCK = 10 NB_BLOCKS = 30 LARGEUR_ECRAN = LARGEUR_BLOCK * NB_BLOCKS s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) def sendData(data): s.sendto(data,(ip_adress,port)) received = s.recvfrom(1024) return received[0] def newGame(): received = sendData('{"type": "new-game"}') return json.loads(received) def update(gameId = 1, direction = None): data = { "type" : "update", "game-id": gameId, "direction": direction } received = sendData(json.dumps(data)) return json.loads(received) # ---------- END SOCKETS ---------- LARGEUR_BLOCK = 20 NB_BLOCKS = 30 LARGEUR_ECRAN = LARGEUR_BLOCK * NB_BLOCKS pygame.init() ecran = pygame.display.set_mode((LARGEUR_ECRAN,LARGEUR_ECRAN)) myfont = pygame.font.SysFont('Comic Sans MS', 20) snakeSprite = pygame.image.load("snake-sprite.png").convert_alpha() snakeSprite = pygame.transform.scale(snakeSprite, (LARGEUR_BLOCK, LARGEUR_BLOCK)) appleSprite = pygame.image.load("apple-sprite.png").convert_alpha() appleSprite = pygame.transform.scale(appleSprite, (LARGEUR_BLOCK, LARGEUR_BLOCK)) def afficher(ecran, snakeCoords, fruitsCoords): snake = [] for coords in snakeCoords: if coords not in snake: snake.append(coords) pygame.draw.rect(ecran, (255,255,255), (0,0,LARGEUR_ECRAN,LARGEUR_ECRAN)) for coords in fruitsCoords: ecran.blit(appleSprite, (coords[0] * LARGEUR_BLOCK, coords[1] * LARGEUR_BLOCK)) for coords in snake: ecran.blit(snakeSprite, (coords[0] * LARGEUR_BLOCK, coords[1] * LARGEUR_BLOCK)) def handleControls(event, gameId): if event.key == pygame.K_LEFT: return update(gameId, 'left') elif event.key == pygame.K_RIGHT: return update(gameId, 'right') elif event.key == pygame.K_UP: return update(gameId, 'down') elif event.key == pygame.K_DOWN: return update(gameId, 'up') else: return None def main(): gameInit = newGame() gameId = gameInit['id'] up = gameInit initSize=len(up['snake']) continuer = True while continuer: afficher(ecran, up['snake'], up['food']) ecran.blit(myfont.render('Score {}'.format(len(up['snake'])-initSize), False, (0, 0, 0)),(0,0)) for event in pygame.event.get(): if event.type == pygame.QUIT: continuer = False elif event.type == pygame.KEYDOWN: updateTmp = handleControls(event, gameId) print(updateTmp) if updateTmp != None and 'type' in updateTmp: if updateTmp['type'] != 'error': up = updateTmp time.sleep(0.3) pygame.display.flip() up = update(gameId) pygame.quit() if __name__ == '__main__': main()