diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..c585e19389d195ff2268d354ecf676d738a578de --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +out \ No newline at end of file diff --git a/README.md b/README.md index 09f9cf70c94163646b7c0cf7f4a1af7febe1684b..1179e61504d3035f01bb39acca169f48995d6136 100644 --- a/README.md +++ b/README.md @@ -1,93 +1,50 @@ -# snakegame +# POP Raylib starter +Simple starter application for POP C assignment. +Please see materials on Blackboard for more details. -## Getting started +# Building -To make it easy for you to get started with GitLab, here's a list of recommended next steps. - -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! - -## Add your files - -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/topics/git/add_files/#add-files-to-a-git-repository) or push an existing Git repository with the following command: +To build run the command: +```bash +/opt/pop/bin/build-wasm.sh src/main.c ``` -cd existing_repo -git remote add origin https://gitlab.uwe.ac.uk/a2-sungur/snakegame.git -git branch -M main -git push -uf origin main -``` - -## Integrate with your tools - -- [ ] [Set up project integrations](https://gitlab.uwe.ac.uk/a2-sungur/snakegame/-/settings/integrations) - -## Collaborate with your team - -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Set auto-merge](https://docs.gitlab.com/user/project/merge_requests/auto_merge/) - -## Test and Deploy - -Use the built-in continuous integration in GitLab. - -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) -*** +This will generate a directory *out* with the WASM and index.html files for the +Raylib program. -# Editing this README +# Running -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template. +The very first time you run a POP WASM application you must run the command: -## Suggestions for a good README - -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. - -## Name -Choose a self-explaining name for your project. - -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. - -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. - -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. - -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. +```bash +/opt/pop/bin/allocate_port.sh +``` -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. +You might need to start a new terminal instance for the update to take effect. +To check that everything is fine run the command: -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. +```bash +echo $MY_PORT +``` -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. +This should output a 5 digit number. -## Contributing -State if you are open to contributions and what your requirements are for accepting them. -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. +To run the Raylib program in *out* simply run the command: -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. +```bash +/opt/pop/bin/run-wasm.sh +``` -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. +This will run a web server that serves the *out* on the port you allocated above. This is forwarded from the +remote server to your local machine, which means you can simply open the corresponding web page within a browser +on your local machine using the address: -## License -For open source projects, say how it is licensed. +```bash +localhost:XXXXX +``` -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. +where *XXXXX* is the port number you allocated above. \ No newline at end of file diff --git a/resources/pop_logo.png b/resources/pop_logo.png new file mode 100644 index 0000000000000000000000000000000000000000..3709225ac8c45af2627a0803eb88ef8fe1ece9f4 Binary files /dev/null and b/resources/pop_logo.png differ diff --git a/resources/pop_logo_small.png b/resources/pop_logo_small.png new file mode 100644 index 0000000000000000000000000000000000000000..f04460cce44ddff7288b71e6dee158d9e670cf14 Binary files /dev/null and b/resources/pop_logo_small.png differ diff --git a/shell.html b/shell.html new file mode 100644 index 0000000000000000000000000000000000000000..71defad5c4d92a412be460fbb083984b8ddba42f --- /dev/null +++ b/shell.html @@ -0,0 +1,301 @@ +<!doctype html> +<html lang="EN-us"> + <head> + <meta charset="utf-8"> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> + + <title>POP Web Game</title> + + <meta name="title" content="POP Raylib Web game"> + <meta name="description" content="POP game using raylib"> + <meta name="keywords" content="raylib, programming, examples, html5, C, C++, library, learn, games, videogames"> + <meta name="viewport" content="width=device-width"> + + + <!-- Favicon --> + <link rel="shortcut icon" href="https://www.raylib.com/favicon.ico"> + + <style> + body { + font-family: arial; + margin: 0; + padding: none; + } + + #header { + width: 100%; + height: 80px; + background-color: #888888; + } + + /* NOTE: raylib logo is embedded in the page as base64 png image */ + #logo { + width:64px; + height:64px; + float:left; + position:relative; + margin:10px; + background-image:url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAACXBIWXMAAAsTAAALEwEAmpwYAAASh0lEQVR4nO2b6XPbZpLGfwRxkABvUtRBXT5kW7Eie+LEM7lm9s/e/bCpTSZO7cSpRD4kx4ckUifFQ7wJgLj2AwGE8shly/GMk9p0FYsQSINv99vH00+/jpjDocf/YxHe9wLet/xhgPe9gPctfxjgfS/gfcuvNoDneXje77eQiBf5cqCo53m4rnvmXiQSIRKJIAgCkUjkHS/zXyevNUCgrOu62LaNbduYoxHWaMRoNMJxHCKRCJIsE4/FiMfjyLJMNBr9XRjiXAMEbu04DqZpohsGg36fTrdLu92m0+nQ7Xbp9/uMRiMigkAykWB6epqFhQVmZmZIJZNIkvSbN8I/GcBxHCzLQtd1Op0OjWaTarXK4eEhx8fH1Op1Wq0W3V4PQ9cZWRZCJEI8Hmdubo61mze5c+cON65fJ5fLIYrib9oIoQEcx2E0GtEfDGg2mxwdHrJbqbCzs8Pe3h7VkxPa7TbD4TB0fcdxzjyssrfH/sEB3W6XaDTKzQ8+IJVKEY1G/+2KvamIALZt0+/3OTo6Yrdc5vnz5zx/8YJypcLJyQn9Xg/dMM5kfEEYF5BIJBLe7/f77OzsIIkixWKRYrFIPB7/TSdG0XEc+v0+z54/5969e/y4scH+3h7N01MGgwG2beN5HpFIBFEUkSUJRVGIxWLEYjFEUcQcjWi32/R6PUajEfsHBzx9+pT19XVmZ2aQZfm3bYBGs8n39+/zn//1X+yW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//H+nKEporKgoIokiQlBFJvqV15XRV8mFDBAMOaaLRT5cWwsTXgCVg10KlJp0TVXTUH0jxCd30DfUZJZ+kx0M1vNr5cJI0LZt2p0OlUqFcqVCt9MJOcRgd1X/pIaiKP+kYBAGk0oGyvwrFHydXBgJBgnOMIwxL+AfawkSjCRJZ5LMqxT8dyj3JvJWUHgSVoYP+o0q+Dp5KyT4e1X2PPlVE4bfs+KB/PHf5t73At63/GGA972A9y3/BxoBDVgEIpmgAAAAAElFTkSuQmCC') + } + + .emscripten { padding-right: 0; margin-left: auto; margin-right: auto; display: block; } + div.emscripten { text-align: center; } + div.emscripten_border { border: 1px solid black; } + + /* NOTE: Canvas *must not* have any border or padding, or mouse coords will be wrong */ + canvas.emscripten { + border: 0px none; + background: black; + width: 512; + height: 512; + } + + .spinner { + height: 30px; + width: 30px; + margin: 0; + margin-top: 20px; + margin-left: 20px; + display: inline-block; + vertical-align: top; + -webkit-animation: rotation .8s linear infinite; + -moz-animation: rotation .8s linear infinite; + -o-animation: rotation .8s linear infinite; + animation: rotation 0.8s linear infinite; + border-left: 5px solid black; + border-right: 5px solid black; + border-bottom: 5px solid black; + border-top: 5px solid red; + border-radius: 100%; + background-color: rgb(245, 245, 245); + } + @-webkit-keyframes rotation { + from {-webkit-transform: rotate(0deg);} + to {-webkit-transform: rotate(360deg);} + } + @-moz-keyframes rotation { + from {-moz-transform: rotate(0deg);} + to {-moz-transform: rotate(360deg);} + } + @-o-keyframes rotation { + from {-o-transform: rotate(0deg);} + to {-o-transform: rotate(360deg);} + } + @keyframes rotation { + from {transform: rotate(0deg);} + to {transform: rotate(360deg);} + } + + #status { + display: inline-block; + vertical-align: top; + margin-top: 30px; + margin-left: 20px; + font-weight: bold; + color: rgb(40, 40, 40); + } + + #progress { + height: 0px; + width: 0px; + } + + #controls { + display: inline-block; + float: right; + vertical-align: top; + margin-top: 15px; + margin-right: 20px; + } + + #output { + width: 100%; + height: 140px; + margin: 0 auto; + margin-top: 10px; + display: block; + background-color: black; + color: rgb(37, 174, 38); + font-family: 'Lucida Console', Monaco, monospace; + outline: none; + } + + input[type=button] { + background-color: lightgray; + border: 4px solid darkgray; + color: black; + text-decoration: none; + cursor: pointer; + width: 140px; + height: 50px; + margin-left: 10px; + } + + input[type=button]:hover { + background-color: #f5f5f5ff; + border-color: black; + } + </style> + </head> + <body> + <div id="header"> + <a id="logo" href="https://www.raylib.com"></a> + + <div class="spinner" id='spinner'></div> + <div class="emscripten" id="status">Downloading...</div> + + <span id='controls'> + <span><input type="button" value="📜 SOURCE CODE" onclick="location.href='https://github.com/raysan5/raylib';"/></span> + <span><input type="button" value="🖵 FULLSCREEN" onclick="Module.requestFullscreen(false, false)"></span> + <span><input type="button" id="btn-audio" value="🔇 MUTE" onclick="toggleAudio()"></span> + </span> + + <div class="emscripten"> + <progress value="0" max="100" id="progress" hidden=1></progress> + </div> + </div> + + <div class="emscripten_border"> + <canvas class="emscripten" id="canvas" oncontextmenu="event.preventDefault()" tabindex=-1></canvas> + </div> + + <textarea id="output" rows="8"></textarea> + + <script type='text/javascript' src="https://cdn.jsdelivr.net/gh/eligrey/FileSaver.js/dist/FileSaver.min.js"> </script> + <script type='text/javascript'> + function saveFileFromMEMFSToDisk(memoryFSname, localFSname) // This can be called by C/C++ code + { + var isSafari = false; // Not supported, navigator.userAgent access is being restricted + //var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); + var data = FS.readFile(memoryFSname); + var blob; + + if (isSafari) blob = new Blob([data.buffer], { type: "application/octet-stream" }); + else blob = new Blob([data.buffer], { type: "application/octet-binary" }); + + // NOTE: SaveAsDialog is a browser setting. For example, in Google Chrome, + // in Settings/Advanced/Downloads section you have a setting: + // 'Ask where to save each file before downloading' - which you can set true/false. + // If you enable this setting it would always ask you and bring the SaveAsDialog + saveAs(blob, localFSname); + } + </script> + <script type='text/javascript'> + var statusElement = document.querySelector('#status'); + var progressElement = document.querySelector('#progress'); + var spinnerElement = document.querySelector('#spinner'); + var Module = { + preRun: [], + postRun: [], + print: (function() { + var element = document.querySelector('#output'); + + if (element) element.value = ''; // Clear browser cache + + return function(text) { + if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' '); + // These replacements are necessary if you render to raw HTML + //text = text.replace(/&/g, "&"); + //text = text.replace(/</g, "<"); + //text = text.replace(/>/g, ">"); + //text = text.replace('\n', '<br>', 'g'); + console.log(text); + + if (element) { + element.value += text + "\n"; + element.scrollTop = element.scrollHeight; // focus on bottom + } + }; + })(), + printErr: function(text) { + if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' '); + + console.error(text); + }, + canvas: (function() { + var canvas = document.querySelector('#canvas'); + + // As a default initial behavior, pop up an alert when webgl context is lost. + // To make your application robust, you may want to override this behavior before shipping! + // See http://www.khronos.org/registry/webgl/specs/latest/1.0/#5.15.2 + canvas.addEventListener("webglcontextlost", function(e) { alert('WebGL context lost. You will need to reload the page.'); e.preventDefault(); }, false); + + return canvas; + })(), + setStatus: function(text) { + if (!Module.setStatus.last) Module.setStatus.last = { time: Date.now(), text: '' }; + if (text === Module.setStatus.last.text) return; + + var m = text.match(/([^(]+)\((\d+(\.\d+)?)\/(\d+)\)/); + var now = Date.now(); + + if (m && now - Module.setStatus.last.time < 30) return; // If this is a progress update, skip it if too soon + + Module.setStatus.last.time = now; + Module.setStatus.last.text = text; + + if (m) { + text = m[1]; + progressElement.value = parseInt(m[2])*100; + progressElement.max = parseInt(m[4])*100; + progressElement.hidden = true; + spinnerElement.hidden = false; + } else { + progressElement.value = null; + progressElement.max = null; + progressElement.hidden = true; + if (!text) spinnerElement.style.display = 'none'; + } + + statusElement.innerHTML = text; + }, + totalDependencies: 0, + monitorRunDependencies: function(left) { + this.totalDependencies = Math.max(this.totalDependencies, left); + Module.setStatus(left ? 'Preparing... (' + (this.totalDependencies-left) + '/' + this.totalDependencies + ')' : 'All downloads complete.'); + }, + //noInitialRun: true + }; + + Module.setStatus('Downloading...'); + + window.onerror = function() { + Module.setStatus('Exception thrown, see JavaScript console'); + spinnerElement.style.display = 'none'; + Module.setStatus = function(text) { if (text) Module.printErr('[post-exception status] ' + text); }; + }; + </script> + + <!-- REF: https://developers.google.com/web/updates/2018/11/web-audio-autoplay --> + <script type='text/javascript'> + var audioBtn = document.querySelector('#btn-audio'); + + // An array of all contexts to resume on the page + const audioContexList = []; + (function() { + // A proxy object to intercept AudioContexts and + // add them to the array for tracking and resuming later + self.AudioContext = new Proxy(self.AudioContext, { + construct(target, args) { + const result = new target(...args); + audioContexList.push(result); + if (result.state == "suspended") audioBtn.value = "🔈 RESUME"; + return result; + } + }); + })(); + + function toggleAudio() { + var resumed = false; + audioContexList.forEach(ctx => { + if (ctx.state == "suspended") { ctx.resume(); resumed = true; } + else if (ctx.state == "running") ctx.suspend(); + }); + + if (resumed) audioBtn.value = "🔇 MUTE"; + else audioBtn.value = "🔈 RESUME"; + } + </script> + {{{ SCRIPT }}} + </body> +</html> \ No newline at end of file diff --git a/src/food.c b/src/food.c new file mode 100644 index 0000000000000000000000000000000000000000..205090351fc62a4c13251f70a526f77a5739adcf --- /dev/null +++ b/src/food.c @@ -0,0 +1,8 @@ +#include "food.h" +#include <stdlib.h> + +// Set food at random position +void SpawnFood(Food *food) { + food->position.x = rand() % (SCREEN_WIDTH / CELL_SIZE); + food->position.y = rand() % (SCREEN_HEIGHT / CELL_SIZE); +} diff --git a/src/food.h b/src/food.h new file mode 100644 index 0000000000000000000000000000000000000000..6036543af2de720798e2a7ed4a13850d2469d0d7 --- /dev/null +++ b/src/food.h @@ -0,0 +1,13 @@ +// Using header files because this helps the compiler know what functions exist before compiling everything, which takes less to compile and makes the program easy to read. +#ifndef FOOD_H +#define FOOD_H + +#include "snake.h" + //simplify red +typedef struct { + Position position; +} Food; + +void SpawnFood(Food *food); + +#endif diff --git a/src/game.c b/src/game.c new file mode 100644 index 0000000000000000000000000000000000000000..6c7bb6b63a3c98af845287491a9598956e1c728f --- /dev/null +++ b/src/game.c @@ -0,0 +1,30 @@ +#include "game.h" +#include <raylib.h> + +// Handle input for snake movement +void HandleInput(Snake *snake) { + if (IsKeyPressed(KEY_RIGHT) && snake->direction.x != -1) { + snake->direction.x = 1; + snake->direction.y = 0; + } + else if (IsKeyPressed(KEY_LEFT) && snake->direction.x != 1) { + snake->direction.x = -1; + snake->direction.y = 0; + } + else if (IsKeyPressed(KEY_UP) && snake->direction.y != 1) { + snake->direction.x = 0; + snake->direction.y = -1; + } + else if (IsKeyPressed(KEY_DOWN) && snake->direction.y != -1) { + snake->direction.x = 0; + snake->direction.y = 1; + } +} + +// Restart game when Enter key is pressed +void ResetGame(Snake *snake, Food *food, int *score, bool *gameOver) { + InitSnake(snake); + SpawnFood(food); + *score = 0; + *gameOver = false; +} diff --git a/src/game.h b/src/game.h new file mode 100644 index 0000000000000000000000000000000000000000..9a7978fc49352c4d2214219c1386b621d67ccf56 --- /dev/null +++ b/src/game.h @@ -0,0 +1,10 @@ +#ifndef GAME_H +#define GAME_H + +#include "snake.h" +#include "food.h" + +void HandleInput(Snake *snake); +void ResetGame(Snake *snake, Food *food, int *score, bool *gameOver); + +#endif diff --git a/src/main.c b/src/main.c new file mode 100644 index 0000000000000000000000000000000000000000..77132442cebf9d165114399cc8a93ec5a5fbffd7 --- /dev/null +++ b/src/main.c @@ -0,0 +1,85 @@ +#include "raylib.h" +#include "snake.h" +#include "food.h" +#include "game.h" +#include <stdlib.h> +#include <time.h> + +int main(void) { + InitWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "Simple Snake Game"); + SetTargetFPS(10); // Snake speed + + srand(time(NULL)); + + Snake snake; + Food food; + + InitSnake(&snake); //center + SpawnFood(&food); + + int score = 0; + bool gameOver = false; + + while (!WindowShouldClose()) { + + if (!gameOver) { + HandleInput(&snake); + UpdateSnake(&snake); + + // Check if food eaten + if (snake.segments[0].x == food.position.x && + snake.segments[0].y == food.position.y) { + score += 1; + if (snake.length < MAX_CELLS) // check and new food appears + snake.length++; + SpawnFood(&food); + } + + // Check for collision + if (CheckCollision(&snake)) + gameOver = true; + + } else { // Game Over state: press Enter to restart + if (IsKeyPressed(KEY_ENTER)) { + ResetGame(&snake, &food, &score, &gameOver); + } + } + + // Rendering + BeginDrawing(); + ClearBackground(RAYWHITE); + + // Draw Snake + for (int i = 0; i < snake.length; i++) { + DrawRectangle(snake.segments[i].x * CELL_SIZE, + snake.segments[i].y * CELL_SIZE, + CELL_SIZE, CELL_SIZE, GREEN); + } + + // Draw Food + DrawRectangle(food.position.x * CELL_SIZE, + food.position.y * CELL_SIZE, + CELL_SIZE, CELL_SIZE, BLUE); + + // Draw Score + DrawText(TextFormat("Score: %d", score), + 10, 10, 20, DARKGRAY); + + // Game Over Message + if (gameOver) { + DrawText("GAME OVER!", SCREEN_WIDTH/2 - MeasureText("GAME OVER!",40)/2, + SCREEN_HEIGHT/2 - 40, 40, GREEN); + DrawText(TextFormat("Final Score: %d", score), + SCREEN_WIDTH/2 - MeasureText("Final Score: XXX",30)/2, + SCREEN_HEIGHT/2 + 10 ,30,DARKGRAY); + DrawText("Press ENTER to Restart", + SCREEN_WIDTH/2 - MeasureText("Press ENTER to Restart",20)/2, + SCREEN_HEIGHT/2 + 50 ,20,LIGHTGRAY); + } + EndDrawing(); + } + + CloseWindow(); + + return 0; +} diff --git a/src/resources/smile.png b/src/resources/smile.png new file mode 100644 index 0000000000000000000000000000000000000000..df2e345ed7cda63f18bd4e20e5b58b9344d35014 Binary files /dev/null and b/src/resources/smile.png differ diff --git a/src/snake.c b/src/snake.c new file mode 100644 index 0000000000000000000000000000000000000000..8204c22131951a7de037ff72b29a3a6d6350326a --- /dev/null +++ b/src/snake.c @@ -0,0 +1,40 @@ +#include "snake.h" + +// center position +void InitSnake(Snake *snake) { + snake->length = 1; + snake->segments[0].x = (SCREEN_WIDTH / CELL_SIZE) / 2; + snake->segments[0].y = (SCREEN_HEIGHT / CELL_SIZE) / 2; + snake->direction.x = 1; + snake->direction.y = 0; +} + +// direction +void UpdateSnake(Snake *snake) { + // Move body segments behind head so the snake is in one piece + for (int i = snake->length - 1; i > 0; i--) { + snake->segments[i] = snake->segments[i - 1]; + } + + // current direction + snake->segments[0].x += snake->direction.x; + snake->segments[0].y += snake->direction.y; +} + +// collision +bool CheckCollision(Snake *snake) { + // Wall + if (snake->segments[0].x < 0 || + snake->segments[0].x >= SCREEN_WIDTH / CELL_SIZE || + snake->segments[0].y < 0 || + snake->segments[0].y >= SCREEN_HEIGHT / CELL_SIZE) + return true; + + // Self + for (int i = 1; i < snake->length; i++) { + if (snake->segments[i].x == snake->segments[0].x && + snake->segments[i].y == snake->segments[0].y) + return true; + } + return false; +} diff --git a/src/snake.h b/src/snake.h new file mode 100644 index 0000000000000000000000000000000000000000..dbc09491e176367b5886d42570b2e81966b43cba --- /dev/null +++ b/src/snake.h @@ -0,0 +1,27 @@ +#ifndef SNAKE_H +#define SNAKE_H + +#include <raylib.h> +#include <stdbool.h> + +#define SCREEN_WIDTH 800 +#define SCREEN_HEIGHT 600 +#define CELL_SIZE 20 +#define MAX_CELLS 1200 +//position +typedef struct { + int x; + int y; +} Position; + +typedef struct { + Position segments[MAX_CELLS]; + int length; + Position direction; +} Snake; + +void InitSnake(Snake *snake); +void UpdateSnake(Snake *snake); +bool CheckCollision(Snake *snake); + +#endif