multiplayer pong game for LPC 1768
Dependencies: mbed MbedJSONValue mbed-rtos Adafruit_ST7735 Adafruit_GFX EthernetInterface DebouncedInterrupt
main.cpp
- Committer:
- vsoltan
- Date:
- 2020-11-23
- Revision:
- 27:fcc5fee18a24
- Parent:
- 26:ebadab157abe
- Child:
- 28:a26a43cdaea8
File content as of revision 27:fcc5fee18a24:
#include "mbed.h" #include "EthernetInterface.h" #include "network.h" #include "gamestate.h" #include "graphics.h" #include "DebouncedInterrupt.h" #include "MbedJSONValue.h" #define DEBOUNCE 25 DebouncedInterrupt leftButton(p21); DebouncedInterrupt middleButton(p22); DebouncedInterrupt rightButton(p23); EthernetInterface eth; UDPSocket sock; Endpoint nist; volatile int count = 0; volatile int sendFlag = 0; volatile int moveData = 0; volatile int menuPress = 0; // interrupts service routines void pressButtonMenu(void) { menuPress = 1; } void pressLeftGame( void ) { sendFlag = 1; moveData -= 5; } void pressRightGame() { sendFlag = 1; moveData += 5; } int main() { initEthernet(ð, &sock, &nist); Graphics *gfx = new Graphics(); // attach ISR leftButton.attach(&pressButtonMenu, IRQ_RISE, DEBOUNCE); middleButton.attach(&pressButtonMenu, IRQ_RISE, DEBOUNCE); rightButton.attach(&pressButtonMenu, IRQ_RISE, DEBOUNCE); MbedJSONValue serverResponse; MbedJSONValue serverRequest; char connectionRequest[] = "{\"type\": \"connected\"}"; char readTo[256]; gfx->renderLaunchScreen(); while (1) { // keep program running if (menuPress) { GameState *gs = new GameState(); // request an open lobby from the server sock.sendTo(nist, connectionRequest, sizeof(connectionRequest) - 1); // change ISRs to game controls leftButton.attach(&pressLeftGame, IRQ_RISE, DEBOUNCE); middleButton.reset(); rightButton.attach(&pressRightGame, IRQ_RISE, DEBOUNCE); while (!gs->done()) { if (sendFlag != 0) { serverRequest["type"] = "move"; serverRequest["hash"] = "jaredyeagersflipflop"; serverRequest["player"] = gs->getLocalPlayerNum(); serverRequest["delta"] = (int)moveData; string requestContent = serverRequest.serialize(); int len = requestContent.size(); char *toSend = (char *)requestContent.c_str(); sendFlag = 0; moveData = 0; sock.sendTo(nist, toSend, len); } int bytesRead = sock.receiveFrom(nist, readTo, sizeof(readTo)); readTo[bytesRead] = 0; if (bytesRead > 0) { printf("data received: %s", readTo); parse(serverResponse, readTo); gs->updateAndRender(&serverResponse, gfx); } wait(.1); } MbedJSONValue dcReq; dcReq["hash"] = "jaredyeagersflipflop"; dcReq["type"] = "disconnect"; string dcReqContent = dcReq.serialize(); int len = dcReqContent.size(); char *dcPayload = (char *)dcReqContent.c_str(); sock.sendTo(nist, dcPayload, len); gfx->renderGameOver(gs); leftButton.attach(&pressButtonMenu, IRQ_RISE, DEBOUNCE); middleButton.attach(&pressButtonMenu, IRQ_RISE, DEBOUNCE); rightButton.attach(&pressButtonMenu, IRQ_RISE, DEBOUNCE); // reset the game menuPress = 0; } wait(0.3); } // cleanupEthernet(ð, &sock); }