diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..61120e942 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +*.DS_Store +node_modules/ +package-lock.json +.gitconfig +.glitch-assets +shrinkwrap.yaml +db.json +public/bundle.js diff --git a/GLITCH-README.md b/GLITCH-README.md new file mode 100644 index 000000000..cb1061b9b --- /dev/null +++ b/GLITCH-README.md @@ -0,0 +1,27 @@ +Welcome to Glitch +================= + +Click `Show` in the header to see your app live. Updates to your code will instantly deploy and update live. + +**Glitch** is the friendly community where you'll build the app of your dreams. Glitch lets you instantly create, remix, edit, and host an app, bot or site, and you can invite collaborators or helpers to simultaneously edit code with you. + +Find out more [about Glitch](https://glitch.com/about). + + +Your Project +------------ + +On the front-end, +- edit `public/client.js`, `public/style.css` and `views/index.html` +- drag in `assets`, like images or music, to add them to your project + +On the back-end, +- your app starts at `server.js` +- add frameworks and packages in `package.json` +- safely store app secrets in `.env` (nobody can see this but you and people you invite) + + +Made by [Glitch](https://glitch.com/) +------------------- + +\ 悜o悜)惎 diff --git a/README.md b/README.md old mode 100755 new mode 100644 index 7f170cdb2..8a27ec08c --- a/README.md +++ b/README.md @@ -1,72 +1,38 @@ -Assignment 4 - Creative Coding: Interactive Multimedia Experiences +LifeGrid === -Due: September 27th, by 11:59 PM. +https://a4-thearst3rd.glitch.me/ -For this assignment we will focus on client-side development using popular audio/graphics/visualization technologies; the server requirements are minimal. The goal of this assignment is to refine our JavaScript knowledge while exploring the multimedia capabilities of the browser. +LifeGrid is an implementation of Conway's Game of Life using three.js to render each cell as an object. This object grows with complexity the longer the cell is alive, growing from a simple sphere to a complex torus knot. -Baseline Requirements ---- +Some challenges I faced: It took me a while to figure out how to go from 2D mouse coordinates to the 3D world coordinates into `(i, j)` coordinates. In fact, I am totally cheesing it based on numbers that _should_ be correct. I tested it out with multiple different window sizes though and it seems to work perfectly. -Your application is required to implement the following functionalities: +Figuring out how to line up all of the mesh elements on the grid took a some time. Eventually I got it, but figuring out the equations and making them all work properly was challenging, because sometimes I would mess it up and all of the elements would be totally off screen and I could not see them at all. -- A server created using Express (you can also use an alternative server framework such as Koa) for basic file delivery and middleware. Your middleware stack should include the `compression` and `helmet` [middlewares]((https://expressjs.com/en/resources/middleware.html)) by default. You are not required to use Glitch for this assignment (but using Glitch is fine!); [Heroku](https://www.heroku.com) is another excellent option to explore. The course staff can't be resposible for helping with all other hosting options outside of Glitch, but some of us do have experience with other systems. It also never hurts to ask on Slack, as there's 99 other classmates who might have the experience you're looking for! -- A client-side interactive experience using at least one of the web technologies frameworks we discussed in class over the past week. - - [Three.js](https://threejs.org/): A library for 3D graphics / VR experiences - - [D3.js](https://d3js.org): A library that is primarily used for interactive data visualizations - - [Canvas](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API): A 2D raster drawing API included in all modern browsers - - [SVG](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API): A 2D vector drawing framework that enables shapes to be defined via XML. - - [Web Audio API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API): An API for audio synthesis, analysis, processing, and file playback. -- A user interface for interaction with your project, which must expose at least six parameters for user control. [dat.gui](https://workshop.chromeexperiments.com/examples/gui/#1--Basic-Usage) is highly recommended for this. You might also explore interaction by tracking mouse movement via the `window.onmousemove` event handler in tandem with the `event.clientX` and `event.clientY` properties. Consider using the [Pointer Events API](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events) to ensure that that mouse and touch events will both be supported in your app. -- Your application should display basic documentation for the user interface when the application first loads. This documentation should be dismissable, however, users should be able to redisplay it via either a help buton (this could, for example, be inside a dat.gui interface) or via a keyboard shortcut (commonly the question mark). -- Your application should feature at least two different ES6 modules that you write ([read about ES6 modules](https://www.sitepoint.com/understanding-es6-modules/)) and include into a main JavaScript file. This means that you will need to author *at least three JavaScript files* (a `app.js` or `main.js` file and two modules). We'll discuss modules in class on Monday 9/23; for this assignment modules should contain at least two functions. -- You are required to use a linter for your JavaScript. There are plugins for most IDEs, however it will be difficult to run the linter directly in Glitch. If you haven't moved to developing on your personal laptop and then uploading to Glitch when your project is completed, this is the assignment to do so! -- Your HTML and CSS should validate. There are options/plugins for most IDEs to check validation. +I used `standard.js` for my linting. All of the javascript files are properly linted as of this submission. It follows a bunch of rules that I actually really do not prefer but it was easy to set up so whatever... Additionally, my website properly validated with both https://validator.w3.org and http://jigsaw.w3.org/css-validator/. Please don't take my word for it - check! -The interactive experience should possess a reasonable level of complexity. Some examples: -### Three.js -- A generative algorithm creates simple agents that move through a virtual world. Your interface controls the behavior / appearance of these agents. -- A simple 3D game -- An 3D audio visualization of a song of your choosing. User interaction should control aspects of the visualization. -### Canvas -- Implement a generative algorithm such as [Conway's Game of Life](https://bitstorm.org/gameoflife/) (or 1D cellular automata) and provide interactive controls. Note that the Game of Life has been created by 100s of people using ; we'll be checking to ensure that your implementation is not a copy of these. -- Design a 2D audio visualizer of a song of your choosing. User interaction should control visual aspects of the experience. -### Web Audio API -- Create a screen-based musical instrument using the Web Audio API. You can use projects such as [Interface.js](http://charlie-roberts.com/interface/) or [Nexus UI](https://nexus-js.github.io/ui/api/#Piano) to provide common musical interface elements, or use dat.GUI in combination with mouse/touch events (use the Pointer Events API). Your GUI should enable users to control aspects of sound synthesis. -### D3.js -- Create visualizations using the datasets found at [Awesome JSON Datasets](https://github.com/jdorfman/Awesome-JSON-Datasets). Experiment with providing different visualizations of the same data set, and providing users interactive control over visualization parameters and/or data filtering. Alternatively, create a single visualization with using one of the more complicated techniques shown at [d3js.org](d3js.org) and provide meaningful points of interaction for users. +The changeable parameters of my application are: +- Running state (on/off) - you can also Single Step through +- How many iterations per second +- How fast the cells' objects rotate +- Editing the board - being able to toggle any cell to be on or off +- The rules of the game - How few cells will cause starvation? How many cells will cause overpopulation? What number of cells will cause a new cell to be born? +- Technically that's only 5 but the rules of the game are 3 different rules, AND the board is 20x20 so really you can change over 400 things in my project :) In all seriousness I do hope that this fulfills the requirements -Deliverables ---- +My two modules are: +- My implementation of the Game of Life game mechanics, and +- A helper that generates my dat.GUI element -Do the following to complete this assignment: +I used browserify to get the two modules inserted for use with the webpage. The command I use is: -1. Implement your project with the above requirements. -3. Test your project to make sure that when someone goes to your main page on Glitch/Heroku/etc., it displays correctly. -4. Ensure that your project has the proper naming scheme `a4-yourname` so we can find it. -5. Fork this repository and modify the README to the specifications below. *NOTE: If you don't use Glitch for hosting (where we can see the files) then you must include all project files that you author in your repo for this assignment*. -6. Create and submit a Pull Request to the original repo. Name the pull request using the following template: `a4-gitname-firstname-lastname`. - -Sample Readme (delete the above when you're ready to submit, and modify the below so with your links and descriptions) ---- - -## Your Web Application Title - -your hosting link e.g. http://a4-charlieroberts.glitch.me - -Include a very brief summary of your project here. Images are encouraged, along with concise, high-level text. Be sure to include: - -- the goal of the application -- challenges you faced in realizing the application -- a brief description of the JS linter you used and what rules it follows (we'll be looking at your JS files for consistency) +`$ browserify public/client.js -o public/bundle.js` ## Technical Achievements -- **Tech Achievement 1**: I wrote my own custom GLSL shaders to use as a material for my Three.js objects. -- **Tech Achievement 2**: My audiovisualizer uses both FFT and amplitude analysis to drive visualization. -- **Tech Achievement 3**: I optimized the efficiency of my reaction-diffusion algorithm by... -- **Tech Achievement 4**: I visualized the dataset X using three different visualization technqiues provided by D3, andprovided +- **Complete Implementation of Conway's Game of Life**: The game is fully, properly implemented. You can change the rules using a dat.GUI menu which allows for some interesting results. +- **Full, efficient board layout using three.js**: I create a small number of geometry and material objects, and then reuse those throughout the board for more efficient memory usage and faster performance. Additionally, I will only change the geometries and materials of the meshes exactly when the contents of the board changes. The objects are not reading the contents of the board every frame, only on the "game" ticks. +- **Adaptable 2D -> 3D Screen Coordinates**: Upon resizing the window, not only does the canvas properly resize itself, but also the mouse input handler recognizes the new size and will properly determine which cell your mouse is hovering over ### Design/Evaluation Achievements -- **Design Achievement 1**: I ensured that my application would run on both desktops / mobile devices by changing X -- **Design Achievement 2**: I followed best practices for accessibility, including providing alt attributes for images and using semantic HTML. There are no `
` or `` elements in my document. -- **Design Achievement 3**: We tested the application with n=X users, finding that... +- **Best Practices**: I followed best practices for accessibility, including providing alt attributes for images and using semantic HTML. There are no `
` or `` elements in my document. This one was actually quite annoying to do because a lot of the examples had full-screen canvases using a `div`. Also, with the popup element, the HTML validator gave me trouble if I kept them all as a `p` element and I needed to split them up into headers without using a `div` or `span`. +- **Mouseover Indication in Edit Mode**: I added a simple transparent cube that will move to the cell that you are hovering over in Edit Mode. +- **Different Models for Each Cell**: I gave different lifespans of each cell a new model and material, so that the board looks much more dynamic. You can observe how long a cell has been alive just by looking at the model and color. diff --git a/package.json b/package.json new file mode 100644 index 000000000..2314fa961 --- /dev/null +++ b/package.json @@ -0,0 +1,33 @@ +{ + "//1": "describes your app and its dependencies", + "//2": "https://docs.npmjs.com/files/package.json", + "//3": "updating this file will download and update your packages", + "name": "hello-express", + "version": "0.0.1", + "description": "A simple Node app built on Express, instantly up and running.", + "main": "server.js", + "scripts": { + "start": "node server.js" + }, + "dependencies": { + "browserify": "^16.5.0", + "compression": "^1.7.4", + "dat.gui": "^0.7.6", + "express": "^4.16.4", + "helmet": "^3.21.1", + "standard": "^14.3.1", + "three": "^0.108.0" + }, + "engines": { + "node": "8.x" + }, + "repository": { + "url": "https://glitch.com/edit/#!/hello-express" + }, + "license": "MIT", + "keywords": [ + "node", + "glitch", + "express" + ] +} diff --git a/public/client.js b/public/client.js new file mode 100644 index 000000000..c177d2baf --- /dev/null +++ b/public/client.js @@ -0,0 +1,350 @@ +/* + * Client-side JS for CS 4241 Assignment 4 + * by Terry Hearst + */ + +const THREE = require('three') +const GameOfLifeModule = require('./gameoflife.js') +const MyDatModule = require('./mydat.js') + +const golBoard = new GameOfLifeModule() + +// ######################## +// ## SETUP GAME OF LIFE ## +// ######################## + +const gridSize = 20 + +function showHelp () { + const popups = document.getElementsByClassName('popup-text') + for (let i = 0; i < popups.length; i++) { + popups[i].classList.toggle('show') + } +} + +const GameOfLifeClass = function () { + this.running = false + this.speed = 3 + this.rotSpeed = 0.6 + this.editMode = false + this.showHelp = showHelp + this.singleStep = function () { + golBoard.runIteration() + this.changed = true + } + + golBoard.setupBoard(gridSize) + this.changed = true +} + +const gameOfLife = new GameOfLifeClass() + +// ################### +// ## SETUP DAT.GUI ## +// ################### + +window.onload = function () { + MyDatModule.init(gameOfLife, golBoard) + + // Show the help screen at the start + showHelp() +} + +// ########################### +// ## SETUP THREE.JS CANVAS ## +// ########################### + +const viewportElement = document.getElementById('viewport') + +const renderer = new THREE.WebGLRenderer() +const canvas = renderer.domElement + +viewportElement.appendChild(canvas) + +const w = canvas.clientWidth +const h = canvas.clientHeight + +console.log('CANVAS SIZE: ', w, h) + +renderer.setSize(w, h) + +// ########################### +// ## SETUP ACTUAL 3D SCENE ## +// ########################### + +// Setup Scene and Camera objs +const scene = new THREE.Scene() +const camera = new THREE.PerspectiveCamera(60, w / h, 0.1, 1000) + +camera.position.z = 11 + +// Create different geometries (and make them all the correct size) +const geos = +[ + /* Blank */ new THREE.Geometry(), + /* Sphere */ new THREE.SphereGeometry(1.3 / (gridSize / 2), 8, 6), + /* Torus */ new THREE.TorusGeometry(1.3 / (gridSize / 2), 0.5 / (gridSize / 2), 8, 16), + /* Knot 1 */ new THREE.TorusKnotGeometry(1.3 / (gridSize / 2), 0.5 / (gridSize / 2), 64, 8, 2, 3), + /* Knot 2 */ new THREE.TorusKnotGeometry(1.5 / (gridSize / 2), 0.45 / (gridSize / 2), 64, 8, 3, 4) +] + +// Create different materials +const mats = +[ + new THREE.MeshStandardMaterial({ color: 0xFF0000 }), + new THREE.MeshStandardMaterial({ color: 0xFFFF00 }), + new THREE.MeshStandardMaterial({ color: 0x30FF30 }), + new THREE.MeshNormalMaterial(/* { color: 0x4040FF } */) +] + +// HELPER - Maps a value from one range to another +function map (x, low1, high1, low2, high2) { + const r1 = high1 - low1 + const r2 = high2 - low2 + return ((x - low1) * (r2 / r1)) + low2 +} + +// HELPER - Calculate x, y position of cell based on i, j index +function calcCellPosition (i, j) { + return { + x: map(i, 0, gridSize - 1, 5 * (-(gridSize - 1) / gridSize), 5 * ((gridSize - 1) / gridSize)), + y: -map(j, 0, gridSize - 1, 5 * (-(gridSize - 1) / gridSize), 5 * ((gridSize - 1) / gridSize)) + } +} + +// Create a mesh for each cell +const meshes = [] +for (let j = 0; j < gridSize; j++) { + meshes[j] = [] + for (let i = 0; i < gridSize; i++) { + const rand1 = Math.floor(Math.random() * 5) + + const mesh = new THREE.Mesh(geos[rand1], mats[rand1 >= 0 ? rand1 - 1 : 0]) + + // Position all meshes in the center of that mesh's square + const cellPosition = calcCellPosition(i, j) + mesh.position.x = cellPosition.x + mesh.position.y = cellPosition.y + + const rotationOffset = Math.random() * Math.PI * 2 + mesh.rotation.x = rotationOffset + mesh.rotation.y = rotationOffset + + scene.add(mesh) + + meshes[j][i] = mesh + } +} + +// TEST - make mesh for the corners of the board +/* +const meshCornerTopLeft = new THREE.Mesh(geos[2], mats[3]) +const meshCornerBottomRight = new THREE.Mesh(geos[3], mats[3]) + +meshCornerTopLeft.position.x = -5 +meshCornerTopLeft.position.y = 5 +meshCornerBottomRight.position.x = 5 +meshCornerBottomRight.position.y = -5 + +scene.add(meshCornerTopLeft) +scene.add(meshCornerBottomRight) +*/ + +// Define lighting +const ambLight = new THREE.AmbientLight(0x303030) +scene.add(ambLight) + +const dirLight = new THREE.DirectionalLight(0xFFFFFF) +const lightTarget = new THREE.Object3D() +lightTarget.position.x = -5 +lightTarget.position.z = -5 +lightTarget.position.y = -5 +scene.add(lightTarget) +scene.add(dirLight) +dirLight.target = lightTarget + +// Make grid +const gridColor = 0x808080 +const gridHelper = new THREE.GridHelper(10, gridSize, gridColor, gridColor) +gridHelper.rotation.x = Math.PI / 2 +scene.add(gridHelper) + +// Make mesh for the object that will assist you in edit mode +const s = 3 / (gridSize / 2) +const editGeo = new THREE.CubeGeometry(s, s, s) +const editMat = new THREE.MeshBasicMaterial({ color: 0xFFFFFF, transparent: true, opacity: 0.3 }) + +const editMesh = new THREE.Mesh(editGeo, editMat) +scene.add(editMesh) + +// ############################ +// ## HANDLE MOUSE MOVEMENTS ## +// ############################ + +// Get screen coords for the board +// Taken from https://stackoverflow.com/questions/27409074/converting-3d-position-to-2d-screen-position-r69 +/* + * NOTE: + * I originally was trying to use the above solution which *apparently* you're supposed to be able to give it an object + * or position (there were variations) that would return the screen space coords. I tried all of them. All of them gave + * me positions of +/- infinity for both x and y. So I use this janky method that WILL WORK assuming that you don't + * change the camera's position. Whatever. + */ +const boardBoundaries = { x1: 0, y1: 0, x2: 0, y2: 0 } +function calculateBoardCornerScreenCoordinates () { + // uhh yeah, I just measured these... + // they work in all resolutions I promise... at least they're close enough + + const top = map(140, 0, 1287, 0, canvas.clientHeight) + const distFromCenter = (canvas.clientHeight / 2) - top + + boardBoundaries.x1 = Math.round((canvas.clientWidth / 2) - distFromCenter) + boardBoundaries.y1 = Math.round((canvas.clientHeight / 2) - distFromCenter) + + boardBoundaries.x2 = Math.round((canvas.clientWidth / 2) + distFromCenter) + boardBoundaries.y2 = Math.round((canvas.clientHeight / 2) + distFromCenter) + + console.log('New board screen coordinates:') + console.log('x1: ', boardBoundaries.x1) + console.log('y1: ', boardBoundaries.y1) + console.log('x2: ', boardBoundaries.x2) + console.log('y2: ', boardBoundaries.y2) +} + +calculateBoardCornerScreenCoordinates() + +window.onmousemove = function (event) { + if (gameOfLife.editMode) { + const i = Math.floor(map(event.x, boardBoundaries.x1, boardBoundaries.x2, 0, gridSize)) + const j = Math.floor(map(event.y, boardBoundaries.y1, boardBoundaries.y2, 0, gridSize)) + + // console.log(i, j) + + if (i >= 0 && i < gridSize && j >= 0 && j < gridSize) { + const cellPosition = calcCellPosition(i, j) + editMat.opacity = 0.3 + + editMesh.position.x = cellPosition.x + editMesh.position.y = cellPosition.y + } else { + editMat.opacity = 0 + } + } else { + editMat.opacity = 0 + } +} + +window.onmousedown = function (event) { + if (gameOfLife.editMode) { + const i = Math.floor(map(event.x, boardBoundaries.x1, boardBoundaries.x2, 0, gridSize)) + const j = Math.floor(map(event.y, boardBoundaries.y1, boardBoundaries.y2, 0, gridSize)) + + if (i >= 0 && i < gridSize && j >= 0 && j < gridSize) { + console.log('Clicked at ', i, j) + golBoard.toggleCell(i, j) + gameOfLife.changed = true + } + } +} + +// ############################## +// ## MAIN RENDERING FUNCTIONS ## +// ############################## + +// Checks to see if the canvas was resized and handles that properly +function resize () { + const width = viewportElement.clientWidth + const height = viewportElement.clientHeight + if (canvas.width !== width || canvas.height !== height) { + // console.log("Canvas resized from ", canvas.width, canvas.height, " to ", width, height) + canvas.clientWidth = width + canvas.clientHeight = height + canvas.width = width + canvas.height = height + + camera.aspect = (width / height) + camera.updateProjectionMatrix() + renderer.setSize(width, height) + + calculateBoardCornerScreenCoordinates() + } +} + +// Update the geometry every frame +// dt - time in seconds since last frame +let elapsed = 0 + +function update (dt) { + resize() + + if (gameOfLife.running) { + elapsed += dt + // console.log(elapsed) + } + + if (elapsed >= (1 / gameOfLife.speed)) { + gameOfLife.changed = true + elapsed -= (1 / gameOfLife.speed) + golBoard.runIteration() + } + + // Set each mesh's properties + if (gameOfLife.changed) { + gameOfLife.changed = false + for (let j = 0; j < gridSize; j++) { + for (let i = 0; i < gridSize; i++) { + const mesh = meshes[j][i] + const cell = golBoard.getCell(i, j) + if (cell.alive) { + if (cell.count < 5) { + mesh.geometry = geos[1] + mesh.material = mats[0] + } else if (cell.count < 8) { + mesh.geometry = geos[2] + mesh.material = mats[1] + } else if (cell.count < 11) { + mesh.geometry = geos[3] + mesh.material = mats[2] + } else /* if (cell.count < 16) */ { + mesh.geometry = geos[4] + mesh.material = mats[3] + } + } else { + mesh.geometry = geos[0] + } + } + } + } + + // Rotate all meshes + for (let j = 0; j < gridSize; j++) { + for (let i = 0; i < gridSize; i++) { + const mesh = meshes[j][i] + mesh.rotation.x += (gameOfLife.rotSpeed * dt) + mesh.rotation.y += (gameOfLife.rotSpeed * dt) + } + } +} + +// Get the timestamp from the previous frame to ensure consistent times even with different framerates +// CODE TAKEN FROM: +// https://codeincomplete.com/posts/javascript-game-foundations-the-game-loop/ +function timestamp () { + return window.performance && window.performance.now ? window.performance.now() : new Date().getTime() +} +let now, dt +let last = timestamp() + +// MAIN render function. This is what should requestAnimationFrame +function render () { + now = timestamp() + dt = (now - last) / 1000 // to get time in seconds + if (dt > 1 / 20) dt = (1 / 20) // will slow down time if framerate dips below 20fps + last = now + + update(dt) + renderer.render(scene, camera) + window.requestAnimationFrame(render) +} + +window.requestAnimationFrame(render) diff --git a/public/gameoflife.js b/public/gameoflife.js new file mode 100644 index 000000000..622fd6d92 --- /dev/null +++ b/public/gameoflife.js @@ -0,0 +1,88 @@ +/* + * Implementation of Conway's Game of Life + * by Terry Hearst + */ + +let gridSize +let board + +// HELPER: returns the number of neighbors of a cell +function getNeighbors (i, j) { + let neighbors = 0 + for (let jj = j - 1; jj < j + 2; jj++) { + for (let ii = i - 1; ii < i + 2; ii++) { + if (ii >= 0 && ii < gridSize && jj >= 0 && jj < gridSize && !(ii === i && jj === j)) { + neighbors += board[jj][ii].alive ? 1 : 0 + } + } + } + return neighbors +} + +// Actual functions exposed by module +module.exports = function () { + this.starvation = 2 + this.overpopulation = 3 + this.birth = 3 + + this.setupBoard = function (_gridSize) { + gridSize = _gridSize + board = [] + for (let j = 0; j < gridSize; j++) { + board[j] = [] + for (let i = 0; i < gridSize; i++) { + const cell = { alive: false, count: 0 } + board[j][i] = cell + } + } + } + + this.getCell = function (i, j) { + return board[j][i] + } + + this.setCell = function (i, j, alive, count) { + const cell = board[j][i] + cell.alive = alive + if (count !== undefined) { + cell.count = count + } + } + + this.toggleCell = function (i, j) { + const cell = board[j][i] + cell.count = 0 + if (cell.alive) { + cell.alive = false + } else { + cell.alive = true + } + } + + this.runIteration = function () { + const newBoard = [] + for (let j = 0; j < gridSize; j++) { + newBoard[j] = [] + for (let i = 0; i < gridSize; i++) { + let newCell + const neighbors = getNeighbors(i, j) + if (board[j][i].alive) { + if (neighbors < this.starvation || neighbors > this.overpopulation) { + newCell = { alive: false, count: 0 } + } else { + newCell = { alive: true, count: board[j][i].count + 1 } + } + } else { + if (neighbors === this.birth) { + newCell = { alive: true, count: 1 } + } else { + newCell = { alive: false, count: 0 } + } + } + newBoard[j][i] = newCell + } + } + + board = newBoard + } +} diff --git a/public/mydat.js b/public/mydat.js new file mode 100644 index 000000000..2c9828702 --- /dev/null +++ b/public/mydat.js @@ -0,0 +1,27 @@ +/* + * Module to set up my dat.GUI + * by Terry Hearst + */ + +const dat = require('dat.gui') + +module.exports = { + init: function (gameOfLife, golBoard) { + const gui = new dat.GUI() + + const f1 = gui.addFolder('Main') + f1.add(gameOfLife, 'running').name('Running') + f1.add(gameOfLife, 'singleStep').name('Single Step') + f1.add(gameOfLife, 'speed', 1, 20).name('Iterations/Sec').step(1) + f1.add(gameOfLife, 'rotSpeed', 0, 5).name('Rotation Speed') + f1.add(gameOfLife, 'editMode').name('Edit Mode') + f1.add(gameOfLife, 'showHelp').name('Toggle Help') + + // f1.open() + + const f2 = gui.addFolder('Change the Rules') + f2.add(golBoard, 'starvation', 0, 8).step(1) + f2.add(golBoard, 'overpopulation', 0, 8).step(1) + f2.add(golBoard, 'birth', 0, 8).step(1) + } +} diff --git a/public/style.css b/public/style.css new file mode 100644 index 000000000..81f357e0d --- /dev/null +++ b/public/style.css @@ -0,0 +1,77 @@ +/* + * Stylesheet for CS 4241 Assignment 4 + * by Terry Hearst + */ + + +/* -- CANVAS STYLING -- */ + +html { + height: 100%; + box-sizing: border-box; +} + +*, *:before, *:after { + box-sizing: inherit; +} + +body { + font-family: monospace; + margin: 0; + height: 100%; +} + +#viewport { + width: 100%; + height: 100%; + background-color: blue; + display: block; +} + +canvas { + width: 100%; + height: 100%; +} + + +/* -- POPUP STYLING -- */ +/* Mostly taken from: */ +/* https://www.w3schools.com/howto/howto_js_popup.asp */ + +.popup { + position: absolute; + display: inline-block; +} + +.popup .popup-text { + visibility: hidden; + width: 400px; + background-color: #555; + color: #fff; + text-align: center; + border-radius: 6px; + padding: 8px; + position: absolute; + z-index: 1; + top: 100px; + left: 100px; +} + +#popup-text-paragraph { + top: 150px; +} + +.popup .popuptext::after { + content: ""; + position: relative; + top: 100%; + left: 50%; + margin-left: -5px; + border-width: 5px; + border-style: solid; + border-color: #555 transparent transparent transparent; +} + +.popup .show { + visibility: visible; +} diff --git a/server.js b/server.js new file mode 100644 index 000000000..aac43a819 --- /dev/null +++ b/server.js @@ -0,0 +1,33 @@ +/* + * Server file for CS 4241 Assignment 4 + * by Terry Hearst + */ + +// ####################### +// ## INITIALIZE SERVER ## +// ####################### + +const express = require('express') +const app = express() +const helmet = require('helmet') +const path = require('path') +const compression = require('compression') + +// Helmet middleware +app.use(helmet()) + +// Compression middleware +app.use(compression()) + +// Host static files +app.use(express.static('public')) + +// Route '/' to main page +app.get('/', function (request, response) { + response.sendFile(path.join(__dirname, 'views', 'index.html')) +}) + +// Listen for requests +const listener = app.listen(process.env.PORT || 3000, function () { + console.log('Your app is listening on port ' + listener.address().port) +}) diff --git a/views/index.html b/views/index.html new file mode 100644 index 000000000..cdcdd0ac6 --- /dev/null +++ b/views/index.html @@ -0,0 +1,36 @@ + + + + + CS 4241 Assignment 4 + + + + + + + + + + +
+ +