simple snake game

Dependencies:   C12832_lcd EthernetInterface WebSocketClient mbed-rtos mbed

main.cpp

Committer:
lyukx
Date:
2016-12-08
Revision:
0:2e5a51003afe

File content as of revision 0:2e5a51003afe:

#include "Snake.h"
#include "mbed.h"
#include "EthernetInterface.h"
#include "Websocket.h"

Serial pc(USBTX, USBRX); // tx, rx

// Joy stick input
DigitalIn joy_left(p13);
DigitalIn joy_right(p16);
DigitalIn joy_up(p15);
DigitalIn joy_down(p12);
DigitalIn fire(p14);

char json_str[2048];

int main(){
    EthernetInterface eth;
    eth.init(); //Use DHCP
    eth.connect();
    printf("IP Address is %s\n", eth.getIPAddress());
    //TCP testing code
    TCPSocketConnection sock;
    sock.connect("mbed.org", 80);
    
    char http_cmd[] = "GET /media/uploads/mbed_official/hello.txt HTTP/1.0\n\n";
    sock.send_all(http_cmd, sizeof(http_cmd)-1);
    
    char buffer[300];
    int ret;
    while (true) {
        ret = sock.receive(buffer, sizeof(buffer)-1);
        if (ret <= 0)
            break;
        buffer[ret] = '\0';
        printf("Received %d chars from server:\n%s\n", ret, buffer);
    }
      
    sock.close();
    // TCP test end
    
    // Websocket Testing Code
    Websocket ws("ws://107.191.61.81:8888/ws");
    ws.connect();
    
    printf("Preparing for net connecting");
    
    //Initial the game screen
    pc.printf("Connected to board...\r\n");

    pc.printf("preparing...");
    Screen scrn;
    SnakeControll ctrl;
    ctrl.init();
    scrn.init();
    scrn.generate_lcd();
    scrn.write_to_screen();
    pc.printf("done. Press joystick to start\r\n");
    while(!fire){}  // Press the joystick to start
    //Game main loop
    while(1){
        char *gamedata = const_cast<char*>(ctrl.get_gamedata().c_str());
        pc.printf(gamedata);
        pc.printf("\r\n");
        ws.send(gamedata);
        ctrl.set_direction(joy_left + joy_right*2 + joy_up*3 + joy_down*4 - 1);
        int flag = ctrl.step();
        if(flag){
            ws.close();
            eth.disconnect();
            exit(0);
        }
        scrn.generate_lcd();
        scrn.write_to_screen();
        wait(0.1);
    }
}