Week 6: Midterm

Midterm Report

Link to Project: https://editor.p5js.org/corbanvilla/full/nXKMcC8T7

Overall Concept

My project is created as a project after an article I wrote for The Gazelle newspaper a couple of years ago, commenting on the often toxic hustle cultured exhibited by NYUAD students. For instance, students often carry around their various responsibilities, commitments, and academic struggles as “badges” that provide social status. In other words, the busier you appear to be, and the less sleep you are getting, the more you are seen as “successful” in our hustle culture. While this type of problem is obviously cannot be generalized to all students, it is certainly applicable to a sizable subset, in my experience. Looking back through my time at NYUAD, there are definitely times where I see myself falling into this trap of quantity over quality.

My project, “Drowning @ NYUAD,” brings this phenomena to life, exaggerating the absurdity of students drowning in commitments. The scoring system of the game is measured in negative hours of sleep–the longer you play, the more sleep you miss. Better scores are proportional to less sleep.

Project Architecture

The architecture of the project was important to me, to ensure that all parts of the code are modular and easily reusable. To that end, all screens of the game are split into different JavaScript files, under the “/screens” subdirectory. They are then imported into the global context under the “index.html” file, and registered into the screen controller in “sketch.js.” Speaking of which, the screen controller (ScreenController class) provides a screen rendering management interface, equipped with a transition animation feature and a “nextScreen” callback function.

To utilize this modularity, screens are “registered” in the order that they should be used in “sketch.js.” Each screen receives a callback function, exposed by the screen controller, that allows any screen to trigger a transition to the next screen at any time. This allowed me to focus on each screen in isolation, without worrying about how screens may overlap or interfere with each other. Furthermore, each screen class then exposes it’s own “draw” method, that is only called when the screen is active. Otherwise, resources are not wasted rendering a background screen. An example of this is shown below:

screenController = new ScreenController();

let nextScreenCallback = screenController.nextScreen.bind(screenController);

screenController.registerScreen(new SplashScreen(nextScreenCallback, gameConfig));
screenController.registerScreen(new CharacterSelectScreen(nextScreenCallback, gameConfig));
screenController.registerScreen(new WeaponSelectScreen(nextScreenCallback, gameConfig));
screenController.registerScreen(new GameScreen(nextScreenCallback, gameConfig));
screenController.registerScreen(new GameOverScreen(nextScreenCallback, gameConfig));

A new JavaScript feature I stumbled upon whilst creating this feature is the “.bind” method. It appeared as an autocomplete suggestion from GitHub copilot while I was writing the code itself. I did not know what “.bind” did, so I asked ChatGPT how it works. It explained that it creates a version of the function, which binds internal references to “.this” to the object it belongs to. Thus, called “.bind” allows me to pass this screen transition function to the various screens. Then, when they call the transition, it will successfully refer to the ScreenController class instance.

Areas for Improvement

One area for improvement that I have identified is a desire to improve the artwork in the game. For instance, while one character is animated, I want to enable the rest of the characters to be animated. Furthermore, I want to animate some of the weapons, such as the triangle ruler, to make it spin as it flies through the air.

I would also like to work on the difficulty of the game. While monsters do begin to spawn faster as time goes on, I want the player’s speed and ammunition speed to also increase, allowing the player to more successfully reach longer stages of the game. Furthermore, I think that power-up abilities, such as those in Mariokart, could be interesting to make the game a bit more balanced.

Screenshots

Here are a few screenshots from the available game screens:

Midterm Project

Concept

My midterm project is an escape room game where the players must follow a series of clues to find different objects around the room. The game begins with a hint that directs the player to the first object. An once it is found, the object reveals a number that the player must remember, as it is part of the final password. The object also provides the next clue, leading the player to the next item in the sequence. This process continues until all objects have been discovered, all of them giving a number needed for the final passcode. To ensure the correct sequence, my game has an ordered clicking type of logic, this means the players can only interact with objects in a specific order. If they attempt to click on an object out of sequence, it will not respond, preventing them from skipping ahead or guessing the passcode incorrectly. This makes sure the players follow the clues and remember the numbers in the right order, so that they can successfully input the password at the end to escape.

link to sketch: https://editor.p5js.org/tfr9406/full/1UNobzqQo

Code Highlights

I think a very important part of my game’s code is the ordered clicking system, which makes sure players find clues in the right order, and prevents them from skipping ahead . To do this I made it so that the code tracks the order of  the interactions using clickOrder and marks visited clues in the visitedClues object. This means, each clue can only be accessed if the previous one has been clicked. For example, the clock must be clicked first (clickOrder === 0) before moving to clue1, then the computer unlocks clue2, and so on until the final clue, the painting, leads to the password page.

I also made it so that the players can revisit clue while keeping the correct order. This is important because it allows players to go back and see the clue again without breaking the structured order. The visitedClues object keeps track of which clues have already been discovered, making sure that once a clue is unlocked, it remains accessible even if the player navigates away and returns. For example, once the player clicks on the clock, visitedClues.clue1 is set to true, meaning they can go back to it at any time. However, they can’t jump ahead to later clues unless they follow the intended order.  This is the code:

if (currentPage === "game") {
  // checks for valid order before allowing to open next clue page
  if (clickOrder === 0 && clock.isClicked(mouseX, mouseY)) {
    currentPage = "clue1";
    clickOrder = 1; // clock clicked first
    visitedClues.clue1 = true; // mark clue1 as visited
  } else if (clickOrder === 1 && computer.isClicked(mouseX, mouseY)) {
    currentPage = "clue2";
    clickOrder = 2; // computer clicked second
    visitedClues.clue2 = true; // mark clue2 as visited
  } else if (clickOrder === 2 && cupboard.isClicked(mouseX, mouseY)) {
    currentPage = "clue3";
    clickOrder = 3; // cupboard clicked third
    visitedClues.clue3 = true; // mark clue3 as visited
  } else if (clickOrder === 3 && books.isClicked(mouseX, mouseY)) {
    currentPage = "clue4";
    clickOrder = 4; // books clicked fourth
    visitedClues.clue4 = true; // mark clue4 as visited
  } else if (clickOrder === 4 && painting.isClicked(mouseX, mouseY)) {
    currentPage = "password"; // move to password page after painting
  }

To get to this final code, I first tested it out with a simpler object and basic logic to make sure the ordered clicking system worked correctly. Initially, I used a minimal setup with just 3 clickable elements and basic variables to track whether an item had been clicked. This helped me confirm that the logic for the sequential interactions was working before expanding it to include the full set of clues and the ability to revisit them. Below was the initial code:

function mousePressed() {
  if (!rectClicked && mouseX > 50 && mouseX < 130 && mouseY > 100 && mouseY < 150) { //first rectangle is clicked
    rectClicked = true;
  } else if (rectClicked && !triClicked && mouseX > 170 && mouseX < 230 && mouseY > 100 && mouseY < 150) { //triangle clicked true  if rectangle clicked first
    triClicked = true;
  } else if (rectClicked && triClicked && !circClicked && dist(mouseX, mouseY, 320, 125) < 25) {//circle clicked true if rectangle and triangle clicked before
    circClicked = true;
    escape = true; //clicking circle = players escapes
  }
}

Challenges

For my game I knew I wanted to implement hover animation to improve overall user experience by providing feedback. However, this was tricky at first because my game page was based on images rather than shapes. Unlike with shapes, where I could easily change the fill color on hover, I had to find a way to replace the whole image itself to give that same visual feedback. To solve this, I created an if-else condition that checks the mouse’s position relative to the designated area for hover. I then updated the image only if the mouse is hovering within the defined boundaries of the clickable area, and also made sure that when the hover condition is not met, the image reverts to its original state, which prevented it from being stuck in the wrong image.

// hover effect 
function handlePageHoverEffects() {
  if (currentPage === "landing") {
    
    // hover for Landing image (switches to landing2 on hover)
    if (mouseX >= 346 && mouseX <= 468 && mouseY >= 337 && mouseY <= 403) {
      currentImage = landing2; // switch to landing2 on hover
    } else {
      currentImage = landing1; // switch back to landing1 otherwise
    }

Improvement

Some of the improvements I could make to the game could maybe include adding different rooms or clues, which would provide more variety and depth to the game. Additionally, introducing difficulty levels would also make the game more accessible to a wider audience. For example, a beginner level with simple clues , and then progressively harder levels with more difficult riddles, hidden objects, and tougher challenges.

 

 

Midterm Project

Final Update: Concept

At first, I wanted my project to recreate my old, cluttered workspace in Bangladesh—full of life, creativity, and memories. But after moving into my dorm, I realized my space now is the opposite: empty, open, and full of possibility.

So instead of a busy, object-filled world, my interactive artwork in p5.js reflects this new beginning. The emptiness isn’t just emptiness—it’s potential. It invites exploration, just like my dorm did when I first moved in. This project became more than just a recreation; it’s a reflection of change, growth, and the spaces we make our own.

️ How It Works

This p5.js sketch opens with a sliding door animation triggered by a double-click—inviting the user into my new, reimagined space. The background is made of looping breathing frames (3 total), giving life to an otherwise still room. All visuals are hand-drawn—hair, furniture, plants, and even a little desktop cat.

Hair animations are split into base, fringe, and left/right segments. Each segment has its own independent frame logic, animated dynamically in code, not as spritesheets—saving memory while giving me more layering control. The breathing and hair create ambient movement that never overwhelms the canvas.

There’s interaction too:

  • Hovering over the lamp activates its glow and animates its arm.

  • Clicking the mirror brings up a live webcam feed. You can “capture yourself” inside the mirror.

  • Clicking the cat opens a surprise sketch.

  • Clicking the Spotify icon links to my actual profile—and starts background music.

I also display a live UAE time clock on the desk monitor, updating every second. Because yes, I coded that too.

 What I’m Proud Of

  • The balance between aesthetics and interaction. I didn’t just cram in clickable objects—I made them meaningful, subtle, and thematic.

  • Hair movement logic. Animating hair in separate segments and syncing their speed gave it a much more natural feel than I could’ve achieved with pre-rendered spritesheets.

  • // Left hair animation
    image(leftHairFrames[currentLeft], xPos - xOffset, yPos - yOffset, hairWidth, hairHeight);
    leftBlend += hairSpeed;
    if (leftBlend >= 1) {
      leftBlend = 0;
      currentLeft = nextLeft;
      nextLeft = (nextLeft + 1) % leftHairFrames.length;
    }
    

     

  • Mirror interaction. Using cam.get() and masking the feed to fit into an oval gave the illusion of a real, personal reflection without needing AR libraries.

  • Sound integration. Audio feedback (the knock, the music) grounds the scene and enhances immersion without stealing the spotlight.

Challenges & Improvements

1. Asset Load Limits & Compression Woes
Initially, I tried creating one big spritesheet for all hair frames—until p5.js (rightfully) panicked. Compressing the sheet butchered the image quality, so I scrapped it in favor of individually loaded and layered PNGs.

// Breathing animation logic
image(breathingFrames[currentFrame], 0, 0, width, height);
tint(255, 255 * blendAmount);
image(breathingFrames[nextFrame], 0, 0, width, height);
blendAmount += fadeSpeed;

if (blendAmount >= 1) {
  blendAmount = 0;
  currentFrame = nextFrame;
  nextFrame = (nextFrame + 1) % breathingFrames.length;
}
noTint();

 

2. Interactivity Clutter
I wanted everything to be interactive. Bad idea. Midway through, I remembered something Professor Mang said: it’s better to be clean and compelling than overloaded. So I scaled back. Some items are just pretty. And that’s fine.

3. Mirror Lag on Some Browsers
Depending on user permissions, the webcam sometimes doesn’t load right. I didn’t implement a fallback system, but it’s something I’d add next time.

 Conclusion

This project started as an homage to an old space but became a meditation on new beginnings. It’s my first time making an ambient interactive piece—part game, part diary, part room. It’s not perfect, but it’s mine. And like any good workspace, it’s full of potential.

Midterm Project

For my midterm project, I decided to do a Space Invaders-inspired shooting game with space ships and aliens. The game was partly inspired by a mobile game called: Radiant. The game’s main feature was an array of weapons in which the player could freely switch between. Because each weapon type had its own advantages and disadvantages, you had to switch between all of them to successfully complete the game. I wanted to incorporate this element into my shooter game to make it more unique and be more interactive and replayable.

Game Design

The game begins on a menu screen, where the player sees the game title and has access to all the instructions they need to play the game. I found a really cool arcade-style font that really matched the theme of the game. Because the game instructions were relatively minimal there was no need to have mutliples screens of text.

Then when the game begins the player is spawned and enemies start spawning from the top of the screen at regular intervals, with the interval decreasing over time to increase the difficulty of the game. The enemies path directly towards the player, ending the game if even one of them touches the player. Because of the number of enemies already present, I did not make the enemies fire any shots.

The player had access to 6 different type of weapons, normal shots, machine gun, shot gun, laser and other settings that all had their own characteristic. The player could switch at anytime by pressing the number keys 1-6. Each type of shot deals different amounts of damage to enemies.

When the player is hit by an enemy the game cuts to a GAME OVER screen. The player can then press play again to restart the game.

Challenges

One problem I continuously faced was when the alien sprites because of the way they were coded, were often the wrong size and unable to be resized by the variables. I had to consult  p5 reference for a while to fix this.

Another problem I had faced for a long time was getting the shot type to switch to the proper type of shots. After tutorials and looking at other projects I switching with cases allowed me to control this as well as shot spread with the keyboard numbers.

Lastly, one thing I was surprised was so challenging was assigning a sound to play when the game ended (I ended up forgoing this). There was no way to easily play a sound once without looping when my game state switched.

  damage = 6
  break
case 4:
  color = [255, 255, 0]
  width = 15
  height = 10
  speed = 12
  damage = 1.5
  break;
case 5:
  color = [255, 50, 255]
  width = 8
  height = 24
  speed = 15
  damage = 3
  break;
case 6: 
  color = [170, 50, 255]
  width = 5
  height = 35
  speed = 25
  damage = 3
  break
}

 

function keyPressed() {
  if (key === '2') {
    shotType = 2
    cooldown = 150
  } else if (key === '1') {
    shotType = 1
    cooldown = 400
  } else if (key === '3') {
    shotType = 3
    cooldown = 800
  } else if (key === '4') {
    shotType = 4
    cooldown = 600
  } else if (key === '5') {
    shotType = 5
    cooldown = 500
  } else if (key === '6') {
    shotType = 6
    cooldown = 600;
  }
}

 

Future Improvements

There are so many ways to potentially improve this game. One way is to definitely have more enemy types that would resist or be weak towards different types of projectiles. This would further incentivise the player to switch weapons, allowing the game to be more engaging.

Another potential improvement is improving the movement patterns of the aliens to be more challenging. If they moved unpredictably towards the player that allowed them to “dodge” shots, the game would have a whole other level of challenge.

Lastly, A scorekeeping method or score in the top left corner would be very useful and would make the game feel like its progressing- this is probably the first change I would want to implement.

Midterm Project

Concept

I’ve always been fascinated by spooky stories, yet wanted to create something more lighthearted than a typical horror game. That is how I ended up making a short, click-based project in which the player buys a haunted house at a bargain price and must purge it of unwanted guests—literally ghosts—to unlock its true potential. From the outset, I imagined a game with a touch of urgency: each wave of ghosts adds just enough pressure to keep your heart rate up, but not so much as to be punishing or relentlessly scary. The result is a game that blends frantic clicking with a fun, eerie atmosphere and a simple storyline that sets the stakes clearly: fail, and the ghosts overwhelm you; succeed, and the house is yours, free of all things that go bump in the night.

To cement that narrative, I designed three distinct levels, each with its own flavor of tension. Level 1’s stationary ghosts ease the player in, Level 2’s moving ghosts ramp up speed and require more hits, and Level 3 features a boss ghost who teleports unpredictably to keep the player on their toes. Across these levels, the fundamental goal never changes—click fast, or you risk running out of time—but the variety of ghost behavior and the gradually intensifying difficulty create a neat progression. The final reward is a bright, newly revealed house, signifying the end of the haunting and the triumph of actually getting to live in your newly bought property.

How the Project Works

The code behind this game employs a simple state machine to orchestrate its various parts. I found this approach more intuitive than cramming all logic into one giant loop. Whenever the player transitions from, say, the INTRO state to LEVEL1, the script calls startLevel(level), which resets the timer, spawns the appropriate ghosts, and ensures there’s no carry-over from earlier states. Here is a small excerpt that illustrates how the game transitions from one level to the next or ends if all ghosts are defeated:

if (ghosts.length === 0) {
  if (level === 1) {
    state = "LEVEL2";
    startLevel(2);
  } else if (level === 2) {
    state = "LEVEL3";
    startLevel(3);
  } else if (level === 3) {
    state = "WIN";
    ghostSound.stop();
    victorySound.play();
  }
}

I’m particularly proud of how coherent each ghost type’s logic is, thanks to object-oriented design. I broke down the ghosts into three classes—StaticGhost, MovingGhost, and BossGhost—so each can handle its own movement and hit requirements. For instance, the MovingGhost class includes velocities in both x and y directions. It updates its position each frame and bounces off the canvas edges, which felt more elegant than scattering if-conditions all over the main draw() loop. This design choice also eases extension: if I someday add a new ghost that splits into two smaller ghosts on hit, I can isolate that behavior in yet another class.

Moreover, I love the inclusion of sound elements, as it heightens the atmosphere. The ghostly background audio starts the moment you tackle Level 1, giving a sense of stepping into a haunted property. On every successful hit, a short “blast” sound triggers, reinforcing the feedback loop for players clicking in a hurry. When the boss ghost is defeated, the game transitions to a “WIN” screen with a triumphant sound, showing off the newly purified house. These little touches bring a pleasant cohesiveness to the otherwise basic act of clicking on sprites and add a layer of fun that purely visual feedback might not achieve.

Areas for Improvement & Challenges Faced

While I’m delighted with the final result, I definitely noticed some spots that could be enhanced through further iteration. First, game balancing was tricky. If I set the time limits too high, the game lost its tension because players could leisurely pick off ghosts. If I made them too strict, new players often found themselves losing before they fully grasped the ghost patterns. I settled on modest values for each level, but it still demands some quick reflexes—if someone isn’t used to rapid clicking, they might find the default times a bit harsh. Introducing difficulty modes, or maybe timed boosts that freeze the ghosts for a short period, would give me more fine control over that difficulty curve and cater to different skill levels.

Another challenge was ensuring that state transitions stayed seamless. At one point, I had ghosts from Level 1 lingering into Level 2, causing the dreaded “two waves at once” bug. The fix involved carefully resetting arrays and timers inside startLevel(level) and confirming no leftover references were carried over. Though it took some debugging, it taught me the importance of thorough housekeeping when cycling through game phases—particularly in an experience that uses back-to-back waves, each with its own unique ghost behaviors. If I expand the project in the future, perhaps adding more levels or extra ghost abilities, I’ll rely heavily on these same organizational principles to keep the code from becoming unwieldy and prone to surprises. I feel the game meets my initial ambition: to craft a short, fun, and spooky challenge that doesn’t overstay its welcome. It balances straightforward gameplay—just point-and-click to vanquish ghosts—with enough variety to keep the three levels distinct and interesting. As I continue refining or building upon the concept, I plan to experiment with new ghost types or reward systems that push the idea even further, but I’m proud of how the current version stands on its own as a playful haunted-house journey.

Midterm Project – Space Shooter

Concept:
My midterm project was inspired by classic arcade games like Space Invaders and Galaga. I wanted to create my own shoot ‘em up game set in space, and try to capture that retro feel while throwing some new elements into the mix.
I made the choice to have the player character and their bullets be pixelated, while the enemies have a more modern look and shoot laser beams in order to create some distinct contrast. I also introduced additional obstacles in the form of slow-moving asteroids and diagonally-moving comets, both of which share in the more modern appearance. I only included sound effects relevant to the player character, so they lean towards the older side.

How it Works:
As for the actual gameplay, I decided to confine the player to a single static screen, where obstacles (including enemies) will continually descend from the top. Since I didn’t design multiple levels or an upward scrolling mechanic, I chose to increase the spawn rate of obstacles as the round goes on to increase the difficulty. The player will continue until their health runs out, at which point they are prompted to save their score.
The player earns points by shooting and destroying an obstacle, but they will also earn a smaller amount for simply allowing the obstacle to pass them and be cleared off-screen. If the player collides with the obstacle, they will instead lose points and destroy the obstacle.

Highlights:
Using OOP to manage different obstacle sub-types + Detecting and handling collisions during gameplay:

class Obstacle {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.radius = 32;
    this.health = 3;
  }
  display() {
    this.update();
    circle(this.x,this.y,this.radius*2);
  }
  update() {
    if (gameRunning()) {
      this.y += 0.5;
    }
  }
  check() {
    if (this.health <= 0) {return}
    // // Flag obstacles below screen to be cleared
    if (!onScreen(this)) {
      // console.log("Destroy offscreen");
      this.health = 0;
      game.score += 5;
    }
    // // Check collision w/ player
    if (checkCollision(this, game.player)) {
      this.health = 0;
      if (!game.player.shielded) {
        game.score -= 10;
        game.player.health -= 1;
        playHurt();
        if (game.player.health <= 0) {return}
        game.player.iframes = 60;
        game.player.shielded = true;
      }
    }
    // // Check collision w/ player bullets
    for (let i = 0; i < game.player.bullets.length; i++) {
      if (checkCollision(this, game.player.bullets[i])) {
        if (!game.player.bullets[i].spent) {
          game.player.bullets[i].spent = true;
          this.health -= 1;
          if (this.health <= 0) {
            game.score += 20;
          }
        }
      }
    }
  }
}
class Enemy extends Obstacle{
  constructor(x, y) {
    // // Gameplay attributes
    super(x, y);
    this.radius = 32;
    this.sprite = enemySprite;
    this.firerate = 0.3;
    this.offset = random(1000);
  }
  display() {
    this.update();
    image(this.sprite, this.x, this.y, 64, 60);
    if (debug) {circle(this.x, this.y, this.radius*2)}
  }
  update() {
    if (gameRunning() && onScreen(this)) {
      this.x += sin((frameCount + this.offset) * 0.05) * 2;
      this.y += 0.5;
      if (triggerFire(this.firerate)) {
        append(game.enemyBullets, new Bullet(
          this.x, this.y+this.radius));
      }
    }
  }
}

Using helper functions instead of cramming everything in-line:

// // Determine whether to shoot on current frame
function triggerFire(rate) {
  let trigger = Math.floor(60 / rate);
  return frameCount %  trigger === 0;
}
// // Check collision of two objects (circle bounding)
function checkCollision(one, two) {
  if (dist(one.x, one.y, two.x, two.y) <= 
      (one.radius + two.radius)) {return true}
  return false;
}
// // Spawn a new enemy/asteroid/comet
function spawnObstacle(type) {
  let newX = Math.floor(random(30, width - 30));
  let newY = Math.floor(random(-50, -200));
  let obs;
  switch(type) {
    case 0:
      obs = new Enemy(newX, newY);
      append(game.enemies, obs);
      break;
    case 1:
      obs = new Asteroid(newX, newY);
      append(game.asteroids, obs);
      break;
    case 2:
      newX = newX % 30;
      obs = new Comet(newX, newY);
      append(game.comets, obs);
      break;
    default:
      console.log("Spawn " + type);
  }
  append(game.obstacles[type], obs);
  if (debug) {console.log("Spawn new " + type)}
}
// // Standardize button styling for menu
function doStyle(elem) {
  // // Styling
  elem.style("font-size", "16px");
  elem.style("font-family", "sans-serif");
  elem.style("background-color", "rgb(20,20,20)");
  elem.style("color", "whitesmoke");
  elem.style("cursor", "pointer");
  // // Hover behaviour
  elem.mouseOver(() => {
    elem.style("background-color", "firebrick");
  });
  elem.mouseOut(() => {
    elem.style("background-color", "rgb(20, 20, 20)");
  });
}
// // Handle gameover
function triggerGameover() {
  gameState = 'gameover';
  game_bgm.stop();
  // player_shoot.stop();
  // player_hurt.stop();
  if (game) {
    game.gameover = true;
    // // Play win sound for score (temp)
    if (game.score > 500) {
      win_sound.play();
      return;
    }
  }
  lose_sound.play();
}

Areas for Improvement:
Since I spent most of my time on the gameplay itself, I feel like I lost out on the visual appeal in several places. For example, my menu screen has some styling on the buttons, but the font is fairly standard instead of using a pixelated font to add to the retro aesthetic. I also had started to work on a leaderboard system, but I belatedly realized that it would download a CSV file to the computer instead of saving the results to the relevant asset file.
Another area for improvement is the gameplay itself. I began to add power ups that would spawn in the playable area, but didn’t have time to fully implement them. The sound design was also a last minute addition that I completely forgot about until I started writing the blog post. Finally, the difficulty ramp-up could use some adjustment. Each obstacle type has semi-randomized parameters within differing bounds, but it still feels like something is a bit off about it.


(Fullscreen)

Midterm Project : Pixel Art

For my midterm project, I drew inspiration from the color-by-number games that are so popular on the internet. I used to be obsessed with them, so I decided to create my own pixelated version. In my project, users color cell by cell in a grid, where each cell corresponds to a letter, and each color on the palette is assigned to a letter as well. By following the key and filling in the grid, the design gradually comes to life, revealing the full picture bit by bit. There’s something incredibly relaxing about mindlessly clicking, watching the colors take shape, and seeing the image emerge one step at a time. It’s a simple yet satisfying process, where every small action contributes to a larger, beautiful result.

The game starts with a welcome screen where the user has two options: Start, to begin coloring immediately, or Help, which provides instructions on the various features the game offers. Once they click Start, they are taken to the selection screen, where they can choose a coloring page from the available options. After selecting a page, they arrive at the actual coloring screen, where the process is simple—choose a color from the palette above and start coloring. However, if the user accidentally fills in the wrong square, they can double-tap the cell to remove the color. If they wish to start over or choose another page, a Reset button clears the canvas. Once the user finishes coloring their chosen page, the game is considered complete, and they are prompted to restart if they wish to play/color again.


One aspect of my code that I’m particularly proud of is the implementation of the actual coloring page. The way the cells fill in over the image has a seamless and polished look. I also like how intuitive the overall user interface is—even first-time users can start playing without needing to read the instructions. I chose soothing shades of brown for the interface, paired with lofi background music, to enhance the game’s relaxing atmosphere.

That said, I encountered a few challenges along the way, particularly with the coloring process itself. One major issue was ensuring that the grid, which tracks cell positions, perfectly aligned with the image. Initially, a double grid effect was visible on top of the image, which was distracting. To fix this, I had to experiment with different parameters before finally finding a formula that worked—provided the image was a perfect square with no empty or extra areas. This was implemented in the ColoringPage class. Once the grid was properly aligned, tracking mouse clicks and filling in the correct areas became much smoother.

class ColoringPage {
  constructor(name, imagePath,thumbPath, rows, cols, palette,targetCells) {
    this.name = name;
    this.img = pageImages[name.toLowerCase()];  
    this.thumb = pageThumbnails[name.toLowerCase()];
    this.rows = rows;
    this.cols = cols;
    this.cellSize = 600 / this.cols;
    this.grid = Array.from({ length: this.rows }, () => Array(this.cols).fill(null));
    this.palette = palette;
    this.selectedColor = Object.values(palette)[0].color;
    this.targetCells = targetCells; 
    this.filledCells = 0;
  }

  display() {
    this.drawPalette();
    image(this.img, 100, 90, 600, 600);
    this.drawGrid();
    this.drawColoredGrid();
  }

  drawGrid() {
    stroke(0, 50);
    noFill();
    for (let row = 0; row < this.rows; row++) {
      for (let col = 0; col < this.cols; col++) {
        rect(100 + col * this.cellSize, 90 + row * this.cellSize, this.cellSize, this.cellSize);
      }
    }
  }

  drawColoredGrid() {
    for (let row = 0; row < this.rows; row++) {
      for (let col = 0; col < this.cols; col++) {
        if (this.grid[row][col]) {
          fill(this.grid[row][col]);
          rect(100 + col * this.cellSize, 90 + row * this.cellSize, this.cellSize, this.cellSize);
        }
      }
    }
  }

  drawPalette() {
    let keys = Object.keys(this.palette);
    let x = (width - keys.length * 60) / 2;
    let y = 20;

    noStroke();

    for (let i = 0; i < keys.length; i++) {
        let colorValue = this.palette[keys[i]].color;
        let isSelected = this.selectedColor === colorValue;
        let isHovered = mouseX > x + i * 60 && mouseX < x + i * 60 + 50 &&
                        mouseY > y && mouseY < y + 50;

        let circleSize = 50; 
        if (isHovered) circleSize = 55; 

        let centerX = x + i * 60 + 30;
        let centerY = y + 25;

        if (isSelected) {
            fill(255); 
            ellipse(centerX, centerY, circleSize + 8, circleSize + 8);
        }

        fill(colorValue);
        ellipse(centerX, centerY, circleSize, circleSize); 
      
      let c = color(colorValue);
      let brightnessValue = (red(c) * 0.299 + green(c) * 0.587 + blue(c) * 0.114); 

        fill(brightnessValue < 128 ? 255 : 0);
        textSize(14);
        textAlign(CENTER, CENTER);
        
        let labelChar = this.palette[keys[i]].label;  
        text(labelChar, centerX, centerY);
    }
}


  selectColor() {
    let keys = Object.keys(this.palette);
    let x = (width - keys.length * 60) / 2;
    for (let i = 0; i < keys.length; i++) {
      if (mouseX > x + i * 60 && mouseX < x + i * 60 + 50 && mouseY > 20 && mouseY < 70) {
        this.selectedColor = this.palette[keys[i]].color;
        break;
      }
    }
  }

  fillCell() {
    let col = floor((mouseX - 100) / this.cellSize);
    let row = floor((mouseY - 90) / this.cellSize);

    if (row >= 0 && row < this.rows && col >= 0 && col < this.cols) {
      if (!this.grid[row][col]) {
        this.grid[row][col] = this.selectedColor;
        this.filledCells++;
        console.log(this.filledCells)
        if (this.isCompleted()) {
          game.state = "final";
        }
      }
    }
  }

Another challenge I faced was determining the end condition for the game. Currently, the game ends when the total number of filled cells matches the number of cells corresponding to a color on the grid. However, this assumes that users only color the cells with assigned letters and don’t fill in any blank spaces. Additionally, since the game allows users to fill any cell with any color, the code does not track whether a specific cell is filled with the correct color. A possible solution would be to store a reference for each cell’s correct color in every coloring page, but I haven’t yet found a way to do this dynamically without hardcoding hundreds of cells, which would be inefficient and take up unnecessary space in the code. This is an area I would like to improve in the future.

Midterm Project – The Magic Studio

Concept

The game is called The Magic Studio. The original idea was to create a highly interactive room where users could generate anything they wanted—sounds, objects, and more—giving them full creative freedom. However, due to time constraints, I scaled the project down to a painting game. In the current version, users are given a reference painting, and they must recreate it by generating objects that match the original as closely as possible. The goal is to maintain an element of creativity while also challenging players to be precise in their recreations.

How it works

The game starts with an instructions screen. It then moves the scene where the user can generate objects to match the desired painting. New objects can be generated by prompting again and the previous one gets removed automatically. Once the user is satisfied with their design, they can click on the next button to move to the next painting. Once all the painting tasks are completed, the user can restart the game.

Challenges

One of the biggest challenges and something that I am the most proud of was making the language model (LLM) generate objects as accurately as possible. Initially, I used a model with limited capabilities, which struggled to create detailed objects correctly. This led to some frustrating results, as the generated objects often didn’t match the intended design. Eventually, I switched to the Gemini model, which significantly improved performance. The new model generated objects more accurately, making the gameplay experience much smoother and more enjoyable.

Another challenge was ensuring that the interaction between the user and the game felt intuitive. Since p5.js is primarily a visual tool, integrating AI-based object generation in a way that seamlessly fit into the game mechanics took a lot of trial and error.

  // Create input field and Gemini button, but hide them until the game starts
  promptInput = createInput("Provide Object Description");
  promptInput.position(350, 100);
  promptInput.hide();
  
  button = createButton("Create your painting!");
  button.position(promptInput.x+20,promptInput.y + promptInput.height + 10);
  button.mousePressed(() => {
    let userText = promptInput.value();
    let geminiPrompt = `
You are an AI code generator working within an online p5.js editor environment. In this environment, the following conditions apply:
- The p5.js library is loaded along with its DOM addon (p5.dom), so functions like createCanvas, createButton, and createInput are available.
- A canvas of 800x600 pixels is created as part of a "dream room" simulation.
- The dream room maintains an array of dream objects. Each dream object must be defined as a JavaScript object with the following properties:
    - x: a numeric value representing the horizontal coordinate (default value: 100)
    - y: a numeric value representing the vertical coordinate (default value: 100)
    - size: a numeric value representing the object’s size (default value: 50)
    - draw: a function that uses p5.js drawing commands (for example, ellipse) to render the object at (x, y) using its size. Ensure you combine multiple shapes for a rich rendering.
    - move: a function that accepts two parameters, dx and dy, and updates the x and y coordinates respectively

Your task is to generate a valid p5.js code snippet that creates a new dream object (named \`dreamObj\`) with these properties. The object must be defined using "let".

Output Requirements:
- Your output must be a valid JSON object with exactly two keys: "code" and "description".
- The "code" key’s value must be a string containing the p5.js code that defines the dream object as described.
- The "description" key’s value must be a concise explanation of what the code does.
- Do not include any additional keys or text; output only the JSON.

Now, generate the object: 
`;
    let prompt = geminiPrompt + userText;
    generateDreamObject(prompt);
  });
  button.hide();

 

Future Improvements

There are the ways I can enhance the project in the future:

  1. AI-Based Scoring System – One idea is to allow players to take a screenshot of their generated painting, and then use AI to analyze it and give a score based on accuracy and similarity to the reference image.
  2. AI-Generated Reference Objects – Instead of only providing a static reference painting, we could allow AI to generate a new image based on the original reference. The AI could create a new rendition of the image in a slightly altered style, and players could then attempt to recreate that version using p5.js.
  3. Comparing AI vs. Player Renderings – We could take screenshots of both the AI-generated image and the player-generated image, then compare them using an AI model to determine which one is a better match to the original reference. This would add another layer of challenge and gamification to the experience.
  4. More Creative Freedom – To bring the project closer to the original concept, I could add more interactive elements, such as sound generation or more diverse object creation tools, allowing users to express their creativity beyond just painting.

Midterm Project Zayed Alsuwaidi

To bring the initial concept of Russian Roulette to life, I decided to use generative AI for the images. I faced several issues sketching the artwork myself on my iPad, and I wanted a surreal realism and impact from the art. The images are therefore generated by DALL-E.

Here are the Game Mechanics:
Players

  • Player: Player starts with 100 health, the bar is at the top-left (50, 50).
  • Opponent: Also 100 health, bar is at top-right (650, 50).
  • Health: Drops by 50 when hit. Game’s over if either of us hits 0.

Gun

  • It’s a 6-shot revolver (shotsFired tracks how many times it’s fired).
  • The chamber’s random—loaded or empty (isLoaded)—and resets on reload.
  • Every shot counts toward the 6, whether it’s a bang or a click.

States

  • “between”: Whether the choice is to shoot (S) or pass (N).
  • “playerTurn”: Player shoots, showing playergun.gif.
  • “opponentTurn”: Person shoots, showing persongun.gif.
  • “reload”: After 6 shots, we reload, and they shoot at me!
  • “gameOver”: One is down; hit R to restart.

My Journey Building It
I started with the basics—getting the images and health bars up. That was smooth, but then I hit a wall with sounds. I added gunshot.m4a for hits, and it worked sometimes, but other times—nothing. That was frustrating. Turns out, browsers block audio until you interact with the page, so I had to trigger it after a key press. Even then, emptyclick.m4a wouldn’t play right when the opponent fired an empty shot. I kept seeing “sound not loaded” in the console and realized the timing was off with setTimeout. I fixed it by storing the shot result in a variable and making sure the sound played every time—loaded or not. Adding the reload mechanic was tricky too; I wanted the opponent to shoot during it, but keeping the flow consistent took some trial and error.

Image:

The image (From DALL-E) I used to depict the person wearing a silk mask covering his facial features and creating a feeling of suspense:

 

 

Gameplay Flow

  1. Start: Game kicks off in “between” with nogun.gif.
  2. My Turn:
    • S: I shoot.
      • Loaded: gunshot.m4a, light flashes, opponent loses 50 health.
      • Empty: emptyclick.m4a, no damage.
    • N: Pass to the opponent.
  3. Opponent’s Turn: They always shoot now (I made it consistent!).
    • Loaded: gunshot.m4a, light flashes, I lose 50 health.
    • Empty: emptyclick.m4a, no damage.
  4. Reload: After 6 shots:
    • Switches to “reload”, shows nogun.gif.
    • Gun resets with a random chamber.
    • Opponent shoots at me:
      • Loaded: gunshot.m4a, light flash, I take damage.
      • Empty: emptyclick.m4a, I’m safe.
    • Back to “between”.
  5. Game Over: When me or the opponent hits 0 health.
    • “Game Over! Press ‘R’ to restart” shows up, and R starts it over.

Controls

  • S: I shoot.
  • N: Pass to the opponent.
  • R: Restart when it’s over.

Visuals

  • Canvas: 800×600—big enough to see everything.
  • Images: Centered at (400, 300), 300×300 pixels.
  • Health Bars: Red base (100 wide), green shrinks as health drops.
  • Light Effect: A cool yellow-white flash when a shot lands—fades out fast.
  • Instructions: Text at the bottom tells me what’s up.

Audio

  • Gunshot: gunshot.m4a for a hit—loud and punchy.
  • Empty Click: emptyclick.m4a for a miss—subtle but tense.
  • Volume: Set both to 0.5 so my ears don’t hate me.

Overcoming Challenges
The sounds were my biggest headache. At first, gunshot.m4a only played after I clicked something—browser rules, ugh. I fixed that by tying it to key presses. Then emptyclick.m4a kept skipping when the opponent shot an empty chamber. I dug into the code and saw the random shoot chance was messing with the timing. I simplified it—stored the shot result, made the opponent shoot every time, and checked isLoaded() right before playing the sound. Now it’s rock-solid.

this.state = "playerTurn";
    this.currentImg = playerGunImg;
    let shotFired = this.gun.shoot();
    if (shotFired) {
      if (gunshotSound.isLoaded()) {
        gunshotSound.play();
      }
      this.opponent.takeDamage();
      this.flashAlpha = 255;
    } else {
      if (emptyClickSound.isLoaded()) {
        emptyClickSound.play();
      }
    }
    setTimeout(() => this.checkReloadOrNext(), 1000);
  }

  opponentTurn() {
    this.state = "opponentTurn";

 to show how I handled the opponent’s turn.

Key Gameplay Highlight

  • Reload Mechanic: The reload’s risky and cool—opponent gets a free shot!
setTimeout(() => {
     let shotFired = this.gun.shoot();
     if (shotFired) {
       if (gunshotSound.isLoaded()) {
         gunshotSound.play();
       }
       this.player.takeDamage();
       this.flashAlpha = 255;
     } else {
       if (emptyClickSound.isLoaded()) {
         emptyClickSound.play();
       }
     }
     setTimeout(() => this.checkReloadOrNext(), 1000);
   }, 1000);
 }

 checkReloadOrNext() {
   if (this.gun.needsReload()) {
     this.reloadGun();
   } else {
     this.nextRound();
   }
 }

 

 

 has the logic for resetting the gun and surviving that tense moment.

Technical Bits

  • Classes:
    • Player: Tracks my health and draws the bar.
    • Gun: Manages the 6-shot limit and random chamber.
    • Game: Runs the show—states, visuals, all of it.
  • p5.js Stuff:
    • preload(): Loads my assets.
    • setup(): Sets up the 800×600 canvas and sound volumes.
    • draw(): Keeps everything on screen.
    • keyPressed(): Listens for S, N, R.

Endgame
It’s over when me or the opponent’s health hits 0. I see “Game Over! Press ‘R’ to restart”, hit R, and it’s back to square one—health full, gun reset.

What’s Next?
Maybe I’ll add a manual reload key or a score counter. Also, I would re-design the game with different artwork to make it more immersive.

Here is a snippet of the state handling, which was key to ensuring less redundancy by preventing procedural programming of the game. Also, the states handle the logic, and this was key in establishing how the game runs i.e if there is an issue with the Game Class, the rest of the gameplay mechanics are directly impacted.

class Game {
  constructor() {
    this.player = new Player("Player", 50, 50); // Player health bar at top-left
    this.opponent = new Player("Opponent", 650, 50); // Opponent health bar at top-right
    this.gun = new Gun();
    this.state = "between"; // States: "between", "playerTurn", "opponentTurn", "reload", "gameOver"
    this.currentImg = noGunImg; // Start with no gun image
    this.flashAlpha = 0; // For light effect transparency
  }

 

 

Midterm Project

Concept

Retro-style 2D shooters have always been a favorite among gamers. Their simplicity, fast-paced action, and pixel-art aesthetics create an engaging experience. I set out to create my own Pixel Shooter Game using p5.js, adding dynamic enemy interactions, ammo management, health pickups, and immersive sound effects.

The idea was simple:

  • The player moves around the screen and shoots at approaching enemies.
  • The enemies chase the player and deal damage upon collision.
  • The player must manage ammo and collect pickups to survive.
  • The game ends when the player’s health reaches zero.

With these mechanics in mind, I designed a game that combines action, strategy, and survival elements.

I used a lot of sound effects from popular shooter games (Half Life, Counter Strike, some soundtracks from Red Faction II) and sandbox games like Minecraft.

I also used free, open-source sprites from different forums, God bless open-source!

How It Works

The game follows a state-based system, transitioning between:

  1. Loading Screen – Displays a progress bar while assets are loading.
  2. Start Menu – Shows the title, “Start Game” and “Instructions” buttons.
  3. Instructions Page – Displays movement, shooting, and gameplay tips.
  4. Play Mode – The core gameplay where enemies chase the player.
  5. Game Over Screen – Displays the final score and an option to restart.

Core Mechanics

  • Player Movement: Uses WASD or arrow keys to move.
  • Shooting: Press Space to fire bullets.
  • Enemy AI: Enemies spawn and move toward the player.
  • Health System: The player starts with 3 HP and dies after three enemy hits.
  • Ammo System: The player has 20 bullets max and must pick up ammo to reload.
  • Pickups: Random enemies drop ammo or health packs.

Code Highlights:

1) State-Based Game Flow

To keep the game organized, I used a state-based approach to control transitions:

function draw() {
  background(20);

  if (gameState === "loading") {
    showLoadingScreen();
    if (assetsLoaded >= totalAssets && loadingCompleteTime === 0) {
      loadingCompleteTime = millis();
    }
    if (loadingCompleteTime > 0 && millis() - loadingCompleteTime > loadingDelay) {
      gameState = "start";
    }
  } 
  else if (gameState === "start") {
    showStartScreen();
    startButton.show();
    instructionsButton.show();
    backButton.hide(); // Ensure Back button is hidden
    
    if (!startMusic.isPlaying()) {
      startMusic.loop();
      startMusic.setVolume(0.5);
    }
  } 
  else if (gameState === "instructions") {
    showInstructionsScreen();
    startButton.hide();
    instructionsButton.hide();
    backButton.show();
  } 
  else if (gameState === "play") {
    runGame();
    showScore();
    startButton.hide();
    instructionsButton.hide();
    backButton.hide();
    
    if (startMusic.isPlaying()) {
      startMusic.stop();
    }
    
    if (!gameMusic.isPlaying()) {
      gameMusic.loop();
      gameMusic.setVolume(0.5);
    }
  } 
  else if (gameState === "dead") {
    showDeadScreen();
    startButton.hide();
    instructionsButton.hide();
    backButton.hide();
  }
}

Each function (showLoadingScreen(), runGame(), etc.) controls what is displayed based on the current state.


2) Player Shooting Mechanic

The player can shoot bullets, but with an ammo limit:

class Player {
  constructor() {
    this.pos = createVector(width / 2, height / 2);
    this.speed = 4;
    this.movementDist = 0; // we update this in update()
    this.ammo = 20;  
    this.health = 3;
    this.lastDamageTime = 0;  // Track last time the player took damage


  }

  update() {
   ...
  }

  show() {
    push();
    translate(this.pos.x, this.pos.y);

    // Face the mouse (common in top-down shooters).
    let angle = atan2(mouseY - this.pos.y, mouseX - this.pos.x);
    rotate(angle);
    scale(0.25);


    // Decide idle or move frames
    let moving = (this.movementDist > 0.1);

    // Pick frame index
    let frameIndex;
      imageMode(CENTER);

    if (moving) {
      frameIndex = floor(frameCount / 6) % playerMoveSprites.length;
      image(playerMoveSprites[frameIndex], 0, 0);
    } else {
      frameIndex = floor(frameCount / 12) % playerIdleSprites.length; 
      image(playerIdleSprites[frameIndex], 0, 0);
    }

    pop();
    
    this.showHealthBar();

  }
  
    showHealthBar() {
    ...
  }

  shoot() {
    // Fire only if enough time has passed since last shot AND we have ammo left
    if (this.ammo > 0 && millis() - lastShotTime > 200) {
      bullets.push(new Bullet(this.pos.x, this.pos.y));
      lastShotTime = millis();
      this.ammo--;  // reduce ammo by 1
    }
    
      if (gunSound) 
        gunSound.play();
  }
}

This ensures players can’t spam bullets, adding a strategic element to gameplay.

3) Enemy AI and Collision Handling

Enemies move toward the player, and if they collide, the player takes damage:

// Enemy-player collisions (Fixed)
for (let enemy of enemies) {
  let dPlayer = dist(player.pos.x, player.pos.y, enemy.pos.x, enemy.pos.y);
  
  // Only take damage if enough time has passed (e.g., 1 second)
  if (dPlayer < 30 && millis() - player.lastDamageTime > 1000) {
    player.health--;  
    player.lastDamageTime = millis(); // Update last hit time
    
    if (hitSound) {
      hitSound.play();
    }
    
    if (player.health <= 0) {
      if(playerDeathSound) {
        playerDeathSound.play();
      }
      gameState = 'dead';
    }
  }
}

This prevents instant death by implementing a damage cooldown.

4) Dynamic Background Music

Different background tracks play in menu and play modes:

else if (gameState === "play") {
  runGame();
  showScore();
  startButton.hide();
  instructionsButton.hide();
  backButton.hide();
  
  if (startMusic.isPlaying()) {
    startMusic.stop();
  }
  
  if (!gameMusic.isPlaying()) {
    gameMusic.loop();
    gameMusic.setVolume(0.5);
  }
}

This immerses the player by dynamically switching music.

Challenges and Improvements

1) Handling Enemy Collisions Fairly

Initially, enemies instantly killed the player if they were touching them. To fix this, I added a damage cooldown, so players have 1 second of immunity between hits.

2) Centering Buttons Properly

Buttons were misaligned when resizing the canvas. Instead of manually placing them, I used dynamic centering.

3) Preventing Accidental Game Starts

Initially, pressing any key started the game. To fix this, I made keyPressed() work only in play mode.

Final Thoughts

This Pixel Shooter Game was a fun challenge that combined:

  • Game physics (enemy movement, shooting mechanics)
  • User experience improvements (better UI, centered buttons)
  • Audio immersion (different music for each state)
  • Optimization tricks (cropping backgrounds, limiting bullet spam)

Possible Future Improvements

  • Add power-ups (e.g., speed boost, rapid fire)
  • Implement different enemy types
  • Introduce a high score system
  • Introduce multiplayer using socket.io (websocket server connection, so two different clients could play on separate machines)

This project demonstrates how p5.js can create interactive, engaging 2D games while keeping code structured and scalable.

Sketch (Click Here to Open Full Screen)