Compare commits

..

No commits in common. "master" and "TCP" have entirely different histories.
master ... TCP

11 changed files with 61 additions and 77 deletions

6
.gitignore vendored
View file

@ -1,8 +1,2 @@
# Ignore tex files
*.tex
# Ignore projects files
**.vscode
# Ignore cache files
**__pycache__

3
.vscode/settings.json vendored Normal file
View file

@ -0,0 +1,3 @@
{
"python.pythonPath": "/usr/bin/python"
}

Binary file not shown.

View file

@ -1,4 +1,3 @@
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
import socket, json, time
import pygame
@ -7,19 +6,25 @@ import pygame
RESP_BUFFER_LENGTH = 1024
ip_adress="192.168.1.14"
port=8080
port=8090
LARGEUR_BLOCK = 10
NB_BLOCKS = 30
LARGEUR_ECRAN = LARGEUR_BLOCK * NB_BLOCKS
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
def connect():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ip_adress,port))
return s
def sendData(data):
s.sendto(data,(ip_adress,port))
received = s.recvfrom(1024)
return received[0]
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ip_adress,port))
s.sendall(data.encode('utf-8'))
s.send('#EOF\n'.encode('utf-8'))
received = s.recv(RESP_BUFFER_LENGTH)
s.close()
return received
def newGame():
received = sendData('{"type": "new-game"}')
@ -34,7 +39,6 @@ def update(gameId = 1, direction = None):
received = sendData(json.dumps(data))
return json.loads(received)
# ---------- END SOCKETS ----------
LARGEUR_BLOCK = 20
@ -43,7 +47,7 @@ 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))
@ -77,29 +81,28 @@ def handleControls(event, gameId):
def main():
gameInit = newGame()
gameId = gameInit['id']
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))
afficher(ecran, up['SNAKE'], up['FOOD'])
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':
if updateTmp != None and 'TYPE' in updateTmp:
if updateTmp['TYPE'] != 'error':
up = updateTmp
time.sleep(0.3)
pygame.display.flip()
time.sleep(0.2)
up = update(gameId)
pygame.display.flip()
pygame.quit()
if __name__ == '__main__':
main()
main()

View file

@ -4,10 +4,14 @@
#+LATEX_HEADER: \usepackage{fullpage}
* General Description
- All transmissions will be based on UDP since latency is important
- All UDP datagrams between *client and server* will contain _plain json data_
- All data should be sent in *one* datagram
- All utf-8 characters in UDP datagram are in lower case
- All transmissions will be based on TCP since:
- Packet length are not fixed (large variance depending on the snake size and food)
- Packet ordering is important (inverted request can compromise gameplay)
- All TCP streams from *client to server* will:
- Contain _plain json data_
- Be terminated by an "#EOF" line (in order for the server to detect the end of the client request)
- All TCP stream from *server to client* will contains _plain json data_ (connection will be closed by the server
so, there is no need of "#EOF").
* Communications
** Initialisation
1. Client sent:
@ -15,6 +19,7 @@
{
"type": "new-game"
}
#EOF
#+END_SRC
2. Server can reply:
#+BEGIN_SRC json
@ -35,6 +40,7 @@
"game-id": 1,
"direction": "left",
}
#EOF
#+END_SRC
2. Then, server can reply:
#+BEGIN_SRC json
@ -54,6 +60,7 @@
"game-id": 1,
"direction": null
}
#EOF
#+END_SRC
2. Server can reply:
#+BEGIN_SRC json

Binary file not shown.

View file

@ -33,7 +33,6 @@
((equal dir "down") (setf (getf p-request :direction) :down))
((equal dir "left") (setf (getf p-request :direction) :left))
((equal dir "right") (setf (getf p-request :direction) :right))))))
((equal type "admin"))
((not (equal type "new-game"))
(error 'bad-request :msg "Unknown request type")))
p-request)))
@ -44,9 +43,8 @@
(let* ((game-id (create-game gm)))
(let ((game-dump (dump gm game-id)))
(setf (getf game-dump :game-over) :null) ; Define nil as null (for json)
(string-downcase
(to-json
(append (list :type "state") game-dump)))))))
(to-json
(append (list :type "state") game-dump))))))
(defmethod handle-update ((api api) data)
(with-slots (gm) api
@ -56,20 +54,9 @@
(if dir
(refresh game :dir dir)
(refresh game))
(string-downcase
(to-json
(append (list :type "state") (dump gm game-id)))))))
(to-json
(append (list :type "state") (dump gm game-id))))))
;;; TODO: debug this function
(defmethod handle-admin ((api api) data)
(with-slots (gm) api
(let* ((game-id (getf data :game-id))
(cmd (getf data :cmd))
(arg (getf data :arg))
(game (get-game gm game-id)))
(cond
((equal cmd "move") (admin game :move arg)))))
"Command executed!")
(defmethod handle-request ((api api) request)
;; Catch request error and send it to the client
@ -79,7 +66,6 @@
(cond
((equal type "new-game") (handle-new-game api data))
((equal type "update") (handle-update api data))
((equal type "admin") (handle-admin api data))
(t (format t "Unknow type"))))
(error (condition) ; Send reason to the client
(let ((reason (make-array 0

View file

@ -21,12 +21,6 @@
:initform nil
:accessor game-over)))
;;; Admin function
(defmethod admin ((g game) &key (move nil move-supplied-p))
(with-slots (snake) g
(when move-supplied-p (setf (nth 0 snake) move))))
;;; Class constructor to initialize the snake
(defmethod initialize-instance :after ((g game) &key)
(with-slots (snake initial-size initial-position) g

View file

@ -4,8 +4,7 @@
(:export
#:game
#:dump
#:refresh
#:admin))
#:refresh))
(defpackage :remote-snake-server-api
(:nicknames :rsapi)
@ -17,7 +16,6 @@
(defpackage :remote-snake-server
(:nicknames :rss)
(:use :common-lisp :usocket :remote-snake-server-api :cl-strings :jonathan)
(:use :common-lisp :usocket :remote-snake-server-api :cl-strings)
(:export
#:start
#:send-cmd))
#:start))

View file

@ -3,7 +3,7 @@
:description "Remote Snake Server."
:version "0.0.1"
:author "Loic Guegan"
:depends-on ( "usocket-server" "jonathan" "cl-strings" )
:depends-on ( "usocket" "jonathan" "cl-strings" )
:components ((:file "packages")
(:module "game"
:depends-on ("packages")

View file

@ -6,25 +6,24 @@
(defparameter *server-buffer* (make-array 10000
:element-type '(unsigned-byte 8)
:initial-element 0))
;;; TODO: debug this function
(defun send-cmd (host port game-id command arg)
(let ((socket (usocket:socket-connect host port :protocol :datagram))
(request (list :type "admin" :cmd command :game-id game-id :arg arg))
(buffer (make-array 500 :element-type '(unsigned-byte 8) :initial-element 0)))
(usocket:socket-send socket (string-downcase (to-json request)) 300)
(format t (babel:octets-to-string (usocket:socket-receive socket buffer 300)))
(force-output t)
(usocket:socket-close socket)))
(defun handle-client (buffer) ; echo
(declare (type (simple-array (unsigned-byte 8) *) buffer)) ; Seems to be to tell lisp which type is buffer
(let ((request (babel:octets-to-string buffer)))
(format t "Receive client request: ~a" request)
(babel:string-to-octets
(handle-request *server-api* request))))
(defun handle-client (client-socket)
(unwind-protect ; To be sure to close the client socket
(let* ((request (read-line (usocket:socket-stream client-socket))))
(loop while (eq (search "#EOF" request) nil) do
(setf request (concatenate 'string request (read-line (usocket:socket-stream client-socket) nil nil))))
(setf request (cl-strings:replace-all request "#EOF" ""))
(format (usocket:socket-stream client-socket) (handle-request *server-api* request))
(force-output (usocket:socket-stream client-socket)))
(usocket:socket-close client-socket)))
;;; The server :D
(defun start (host port)
(usocket:socket-server host port #'handle-client nil :in-new-thread nil :protocol :datagram))
(defun start (interface port)
(format t "Server started!~%")
(let ((socket (usocket:socket-listen interface port)))
(unwind-protect ; To be sure to close server socket
(loop
(handle-client (usocket:socket-accept socket :element-type 'character)))
(usocket:socket-close socket))))