From 9afd7adc5e1b05042acdd5649efec84a5de47920 Mon Sep 17 00:00:00 2001 From: MargaretEarnest Date: Sun, 11 Oct 2020 22:49:25 -0400 Subject: [PATCH 1/3] Updated readme --- README.md | 62 +++++-------------------------------------------------- 1 file changed, 5 insertions(+), 57 deletions(-) diff --git a/README.md b/README.md index b61d3e2b..01804d57 100644 --- a/README.md +++ b/README.md @@ -1,59 +1,7 @@ -Assignment 4 - Creative Coding: Interactive Multimedia Experiences -=== +## Customizable Tetris -Due: October 11th, by 11:59 PM. +Margaret Earnest +https://a4-margaret-earnest.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. - -Baseline Requirements ---- - -Your application is required to implement the following functionalities: - -- A server created using Express. This server can be as simple as needed. -- A client-side interactive experience using at least one of the following web technologies frameworks. - - [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 HTML and CSS should validate. There are options/plugins for most IDEs to check validation. - -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. - -Deliverables ---- - -Do the following to complete this assignment: - -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-firstname-lastname` 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-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 when needed, along with concise, high-level text. Be sure to include: - -- the goal of the application -- challenges you faced in realizing the application -- the instructions you present in the website should be clear enough to use the application, but if you feel any need to provide additional instructions please do so here. +This application is a Tetris game with some user-defined options. These options include color scheme, control setup, background music, falling delay, whether or not the speed increase throughout the game, and whether the game is played in dark mode. After defining settings, users can play tetris with their options enabled. +I faced a number of challenges while making this game. One was allowing pieces to retain their color when they land. To do this I had to store all the previous piece objects as well as the currently falling piece object. I also had trouble getting the score badge to scale with increases in score, an issue which I fixed in the javascript rather than in the CSS. \ No newline at end of file From fdf373ee4c7eb5b8fdfd2c3cf092e3ecac78f168 Mon Sep 17 00:00:00 2001 From: MargaretEarnest Date: Sun, 11 Oct 2020 22:56:43 -0400 Subject: [PATCH 2/3] Initial commit --- package.json | 19 +++ public/script.js | 325 +++++++++++++++++++++++++++++++++++++++++++++++ public/style.css | 51 ++++++++ server.js | 21 +++ views/index.html | 96 ++++++++++++++ 5 files changed, 512 insertions(+) create mode 100644 package.json create mode 100644 public/script.js create mode 100644 public/style.css create mode 100644 server.js create mode 100644 views/index.html diff --git a/package.json b/package.json new file mode 100644 index 00000000..dd7ea6a3 --- /dev/null +++ b/package.json @@ -0,0 +1,19 @@ +{ + "name": "Customizable-Tetris", + "version": "0.0.1", + "description": "A tetris game following user-defined settings", + "main": "server.js", + "scripts": { + "start": "node server.js" + }, + "dependencies": { + "express": "^4.17.1", + "nes.css": "^2.3.0" + }, + "engines": { + "node": "12.x" + }, + "repository": { + "url": "https://a4-margaret-earnest.glitch.me/" + } +} diff --git a/public/script.js b/public/script.js new file mode 100644 index 00000000..1028d516 --- /dev/null +++ b/public/script.js @@ -0,0 +1,325 @@ +function loadInstruct() { + var coll = document.getElementsByClassName("collapsible"); + console.log(coll[0]) + + for(let i = 0; i < coll.length; i++) { + coll[i].addEventListener("click", function() { + console.log("clicked") + this.classList.toggle("active"); + var content = this.nextElementSibling; + if (content.style.display === "block") { + content.style.display = "none"; + } else { + content.style.display = "block"; + } + }); + } +} + +var colors = [ + ["#952D98", "#FF7900", "#ED2939", "#FECB00", "#69BE28", "#0065BD", "#009FDA"], + ["#FF0018", "#FFA52C", "#FFFF41", "#008018", "#0000F9", "#86007D", "#ee82ee"], + ["#D8BFD8", "#DDA0DD", "#EE82EE", "#FF00FF", "#8A2BE2", "#4B0082", "#800080"], + ["#A0A0A0", "#D0D0D0", "#B0B0B0", "#909090", "#696969", "#484848", "#202020"] +]; +var keys = [["ArrowUp", "ArrowLeft", "ArrowRight", "ArrowDown"], + ["w","a","d","s"]] +//Tetris themes were taken from the original Tetris soundtrack +var songs = ["https://cdn.glitch.com/e7b8999b-7138-470c-8319-d98ed52a8af5%2FTheme1.mp3?v=1602463005030", "https://cdn.glitch.com/e7b8999b-7138-470c-8319-d98ed52a8af5%2FTheme2.mp3?v=1602462758615", "https://cdn.glitch.com/e7b8999b-7138-470c-8319-d98ed52a8af5%2FTheme3.mp3?v=1602462757540", ""] + +function runGame() { + if(document.getElementById("enableDark").checked) { + document.body.style.backgroundColor = "black"; + document.getElementsByTagName("H1")[0].style.color = "white"; + document.getElementById("delayLabel").style.color = "white"; + var all = document.getElementsByTagName("*"); + for (var i=0, max=all.length; i < max; i++) { + if(!all[i].tagName == "canvas") { + all[i].classList.add("is-dark"); + } + } + document.getElementById("canvas").style.border = "solid white"; + lineColor = "white"; + } else { + document.body.style.backgroundColor = "white"; + document.getElementsByTagName("H1")[0].style.color = "black"; + document.getElementById("delayLabel").style.color = "black"; + var all = document.getElementsByTagName("*"); + for (var i=0, max=all.length; i < max; i++) { + all[i].classList.remove("is-dark"); + } + document.getElementById("canvas").style.border = "solid black"; + lineColor = "black"; + } + c = document.getElementById("canvas"); + h = c.height; + w = c.width; + ctx = c.getContext("2d"); + ctx.lineWidth = 0.5; + //vary colors row by color radio selection to get different color palettes + let palette = document.querySelector('input[name="color"]:checked').value; + keyChoice = document.querySelector('input[name="key"]:checked').value; + const T = { + piece: [[0, 0, 0], [1, 1, 1], [0, 1, 0]], + color: colors[palette][0], + pos: [3, -1] + }; + const J = { + piece: [[0, 0, 0], [1, 1, 1], [0, 0, 1]], + color: colors[palette][1], + pos: [3, -1] + }; + const Z = { + piece: [[0, 0, 0], [1, 1, 0], [0, 1, 1]], + color: colors[palette][2], + pos: [3, -1] + }; + const O = { piece: [[1, 1], [1, 1]], color: colors[palette][3], pos: [3, 0] }; + const S = { + piece: [[0, 0, 0], [0, 1, 1], [1, 1, 0]], + color: colors[palette][4], + pos: [3, -1] + }; + const L = { + piece: [[0, 0, 0], [1, 1, 1], [1, 0, 0]], + color: colors[palette][5], + pos: [3, -1] + }; + const I = { + piece: [[0, 0, 0, 0], [0, 0, 0, 0], [1, 1, 1, 1], [0, 0, 0, 0]], + color: colors[palette][6], + pos: [3, -1] + }; + pieces = [T, J, Z, O, S, L, I]; + music.pause(); + music = new Audio(songs[document.querySelector('input[name="song"]:checked').value]); + music.play(); + maxTimer = document.getElementById("delay").value; + increase = document.getElementById("enableIncrease").checked; + reset(); + draw(); +} + +var board; +var piecePos; +var currentPiece; +var timer; +var maxTimer; +var prevBoard; +var score; +var c; +var h; +var w; +var ctx; +var pieces; +var keyChoice; +var music = new Audio(""); +var increase; +var lineColor; +var justFlipped = false; + +//https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array +function shufflePieces(pieces) { + for (let i = pieces.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [pieces[i], pieces[j]] = [pieces[j], pieces[i]]; + } +} + +// modified form of https://stackoverflow.com/questions/17428587/transposing-a-2d-array-in-javascript +function rot(array) { + var newArray = []; + for (var row = 0; row < array[0].length; row++) { + newArray.push([]); + } + + for (var row = 0; row < array[0].length; row++) { + for (var col = array.length - 1; col >= 0; col--) { + newArray[row].push(array[col][row]); + } + } + + return newArray; +} + +function arrCopy(baseArr, copyArr, startC, startR) { + let newArr = JSON.parse(JSON.stringify(baseArr)); + for (let r = 0; r < copyArr.length; r++) { + for (let c = 0; c < copyArr[0].length; c++) { + if (startR + r > newArr.length - 1) { + console.log("Piece hit bottom"); + if (copyArr[c][r]) { + return null; + } else { + continue; + } + } else if (startC + c < 0 && copyArr[c][r]) { + console.log("Left Collision"); + currentPiece.pos[0]++; + return "Continue"; + } else if (startC + c > newArr[0].length - 1 && copyArr[c][r]) { + console.log("Right Collision"); + currentPiece.pos[0]--; + return "Continue"; + } else if (newArr[startR + r][startC + c] && copyArr[c][r]) { + console.log("Collision with piece"); + return null; + } else if (!newArr[startR + r][startC + c] && copyArr[c][r]) { + //case where there is an empty space that would be filled + newArr[startR + r][startC + c] = currentPiece; + } + } + } + return newArr; +} + +function update(arr, ctx) { + ctx.clearRect(0, 0, w, h); + for (var i = 0; i < arr.length; i++) { + var row = arr[i]; + for (var j = 0; j < row.length; j++) { + if (row[j] != 0) { + ctx.fillStyle = row[j].color; + ctx.fillRect((j * w) / 10, (i * h) / 20, 20, 20); + } + } + } + ctx.strokeStyle = lineColor; + for (let i = w / 10; i < w; i += w / 10) { + ctx.beginPath(); + ctx.moveTo(i, 0); + ctx.lineTo(i, h); + ctx.stroke(); + } + + for (let i = h / 20; i < h; i += h / 20) { + ctx.beginPath(); + ctx.moveTo(0, i); + ctx.lineTo(w, i); + ctx.stroke(); + } + document.getElementById("score").innerText = "Score: " + score; + document.getElementById("badge").style.cssText = + "width:" + (150 + 15 * score.toString().length) + "px !important"; +} + +function checkGameOver() { + for (var i = 0; i < board[0].length; i++) { + if (board[0][i] != 0) { + return true; + } + } + return false; +} + +function handleFullRow() { + let count = 0; + for (var i = 0; i < board.length; i++) { + if (!board[i].includes(0)) { + board.splice(i, 1); + board.unshift(Array(10).fill(0)); + count++; + if(increase && maxTimer > 0) { + maxTimer -= 5; + } + } + } + switch (count) { + case 1: + score += 100; + break; + case 2: + score += 300; + break; + case 3: + score += 500; + break; + case 4: + score += 800; + break; + } +} + +function reset() { + board = Array(20) + .fill() + .map(() => Array(10).fill(0)); + shufflePieces(pieces); + piecePos = 0; + currentPiece = JSON.parse(JSON.stringify(pieces[piecePos])); + timer = 0; + prevBoard = null; + score = 0; + window.scrollTo(0,0); +} + +function updateBoard() { + let tryBoard = arrCopy( + board, + currentPiece.piece, + currentPiece.pos[0], + currentPiece.pos[1] + ); + if (tryBoard != null && tryBoard != "Continue") { + update(tryBoard, ctx); + prevBoard = tryBoard; + justFlipped = false; + } else if (tryBoard == null) { + if (justFlipped) { + gameOver() + } + board = prevBoard; + if (piecePos > 5) { + piecePos = 0; + shufflePieces(pieces); + } else { + piecePos++; + } + currentPiece = JSON.parse(JSON.stringify(pieces[piecePos])); + justFlipped = true; + } +} + +function draw() { + if (new Date().getTime() - timer > maxTimer) { + timer = new Date().getTime(); + currentPiece.pos[1]++; + updateBoard(); + handleFullRow(); + } + if (checkGameOver()) { + gameOver() + } else { + window.requestAnimationFrame(draw); + } +} + +function gameOver() { + ctx.font = "24px Arial"; + ctx.fillStyle = "black"; + ctx.fillRect(0, 0, w, h); + ctx.fillStyle = "white"; + ctx.textAlign = "center"; + ctx.fillText("Game Over", w / 2, h / 2); + window.requestAnimationFrame(draw); +} + +addEventListener("keydown", function(event) { +if (event.key == keys[keyChoice][0]) { + event.preventDefault(); + currentPiece.piece = rot(currentPiece.piece); + updateBoard(); + } else if (event.key == keys[keyChoice][1]) { + event.preventDefault(); + currentPiece.pos[0]--; + updateBoard(); + } else if (event.key == keys[keyChoice][2]) { + event.preventDefault(); + currentPiece.pos[0]++; + updateBoard(); + } else if (event.key == keys[keyChoice][3]) { + event.preventDefault(); + currentPiece.pos[1]++; + updateBoard(); + } +}); \ No newline at end of file diff --git a/public/style.css b/public/style.css new file mode 100644 index 00000000..2afd59aa --- /dev/null +++ b/public/style.css @@ -0,0 +1,51 @@ +canvas { + height:400px; + width:200px; + border:solid; +} + +body { + width: 90%; + margin:auto; + font-family: 'Press Start 2P', cursive; +} + +#badge, button, canvas { + display:block; + margin:auto !important; +} + +h1 { + text-align:center; +} + +.nes-container, .nes-field { + width: 50% !important; + margin:auto !important; +} + +/* Collapsible is based on W3 schools example */ +.collapsible { + background-color: #777; + color: white; + cursor: pointer; + padding: 18px; + width: 50%; + border: none; + text-align: left; + outline: none; + font-size: 15px; +} + +.active, .collapsible:hover { + background-color: #555; +} + +.content { + padding: 0 18px; + margin:auto; + width: 50%; + display: block; + overflow: hidden; + background-color: #f1f1f1; +} \ No newline at end of file diff --git a/server.js b/server.js new file mode 100644 index 00000000..5723d8b6 --- /dev/null +++ b/server.js @@ -0,0 +1,21 @@ +// server.js +// where your node app starts + +// we've started you off with Express (https://expressjs.com/) +// but feel free to use whatever libraries or frameworks you'd like through `package.json`. +const express = require("express"); +const app = express(); + +// make all the files in 'public' available +// https://expressjs.com/en/starter/static-files.html +app.use(express.static("public")); + +// https://expressjs.com/en/starter/basic-routing.html +app.get("/", (request, response) => { + response.sendFile(__dirname + "/views/index.html"); +}); + +// listen for requests :) +const listener = app.listen(process.env.PORT, () => { + 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 00000000..eb872854 --- /dev/null +++ b/views/index.html @@ -0,0 +1,96 @@ + + + + + + + + Customizable Tetris + + + + + + + +

Customizable Tetris


+
+ Score: 0 +

+ Your browser doesn't support canvas :(
+
+ + +
+
+

Welcome to Customizable Tetris! Use the options below to play Tetris however you like best. You can change the color scheme, change the input type, and turn on background music. You can also set the falling delay, which determines how slowly pieces fall. The higher the delay value the slower pieces will fall, with normal values ranging between 100 and 600. The following checkbox lets you turn on a progressive speed increase as lines are cleared. Finally, dark mode can be enabled at the end of the menu. Click the instructions button above to toggle this section's visibility.

+
+

+ +
+

Color Scheme

+ + + + +

+
+

Control Keys

+ + +

+
+

Background Music

+ + + + +

+
+ + +

+
+ +

+
+ +

+ + From ec3154fbee5ffdf0a08534acddce9481a5ea851f Mon Sep 17 00:00:00 2001 From: MargaretEarnest Date: Sun, 11 Oct 2020 23:02:14 -0400 Subject: [PATCH 3/3] Fixed piece orientations --- public/script.js | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/public/script.js b/public/script.js index 1028d516..48fa8ac9 100644 --- a/public/script.js +++ b/public/script.js @@ -17,7 +17,7 @@ function loadInstruct() { } var colors = [ - ["#952D98", "#FF7900", "#ED2939", "#FECB00", "#69BE28", "#0065BD", "#009FDA"], + ["#952D98", "#FF7900", "#69BE28", "#FECB00", "#ED2939", "#0065BD", "#009FDA"], ["#FF0018", "#FFA52C", "#FFFF41", "#008018", "#0000F9", "#86007D", "#ee82ee"], ["#D8BFD8", "#DDA0DD", "#EE82EE", "#FF00FF", "#8A2BE2", "#4B0082", "#800080"], ["#A0A0A0", "#D0D0D0", "#B0B0B0", "#909090", "#696969", "#484848", "#202020"] @@ -60,33 +60,33 @@ function runGame() { let palette = document.querySelector('input[name="color"]:checked').value; keyChoice = document.querySelector('input[name="key"]:checked').value; const T = { - piece: [[0, 0, 0], [1, 1, 1], [0, 1, 0]], + piece: rot([[0, 0, 0], [1, 1, 1], [0, 1, 0]]), color: colors[palette][0], pos: [3, -1] }; const J = { - piece: [[0, 0, 0], [1, 1, 1], [0, 0, 1]], + piece: rot([[0, 0, 0], [1, 1, 1], [0, 0, 1]]), color: colors[palette][1], pos: [3, -1] }; const Z = { - piece: [[0, 0, 0], [1, 1, 0], [0, 1, 1]], + piece: rot([[0, 0, 0], [1, 1, 0], [0, 1, 1]]), color: colors[palette][2], pos: [3, -1] }; - const O = { piece: [[1, 1], [1, 1]], color: colors[palette][3], pos: [3, 0] }; + const O = { piece: rot([[1, 1], [1, 1]]), color: colors[palette][3], pos: [3, 0] }; const S = { - piece: [[0, 0, 0], [0, 1, 1], [1, 1, 0]], + piece: rot([[0, 0, 0], [0, 1, 1], [1, 1, 0]]), color: colors[palette][4], pos: [3, -1] }; const L = { - piece: [[0, 0, 0], [1, 1, 1], [1, 0, 0]], + piece: rot([[0, 0, 0], [1, 1, 1], [1, 0, 0]]), color: colors[palette][5], pos: [3, -1] }; const I = { - piece: [[0, 0, 0, 0], [0, 0, 0, 0], [1, 1, 1, 1], [0, 0, 0, 0]], + piece: rot([[0, 0, 0, 0], [0, 0, 0, 0], [1, 1, 1, 1], [0, 0, 0, 0]]), color: colors[palette][6], pos: [3, -1] };