Final Project : SPACE SURVIVAL 🚀💫

Description of the Assignment: 

Create a physically interactive system of your choice that relies on a multimedia computer for some sort of processing or data analysis. The Final should use BOTH Processing AND Arduino.Your focus should be on careful and timely sensing of the relevant actions of the person or people that you’re designing this for, and on clear, prompt, and effective responses. Any interactive system is going to involve systems of listening, thinking, and speaking from both parties. Whether it involves one cycle or many, the exchange should be engaging. You may work alone or in pairs.

Description of the Projects: 

This game is a typical 90s arcade space shooter game where you control a space ship and shoot bullets at the asteroid to protect yourself. In this version of the game, instead of using the basic key controls, the player uses the motions of the hand to control the space ship and shoot bullets at the asteroid.

Process: 

The  command for the motion of the ship is given via the ultrasonic sensor.The distance between the players hand and the ultrasonic sensor determines the x-coordinate  of the ship in the game. I used the   to detect the change in light when the player closes his/her fist to shoot bullets. I mapped the sensor reading from 0 to 1023, to 0 to 10. Then I divided the readings into 2. When the photoresistor read above or equal to 5, the bullets would shoot, and the red light would light up, otherwise the blue led would light up indicating that the value is below 5.

For the processing , I created stars and asteroid in a loop as a separate function by putting them in an Array with random values across the width of the screen. The values for the bullets too are kept in an Array, but their x coordinate starts from the x-coordinate of the ship +100 (center of the ship) and the same as y -coordinate of the ship . For the spaceship, I used the following picture, resized to 200 by 100.

 

Here is also a picture of the overall set up:

 

Video: 

 

Code: 

Arduino:

int left = 0;
int right = 0;
//int buzzer = 5;

const int echoPin = 2;  // attach pin D2 Arduino to pin Echo of HC-SR04
const int trigPin = 3; //attach pin D3 Arduino to pin Trig of HC-SR04

const int led_red = 9;
const int led_blue = 8;
const int photo = A0;


// defines variables
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement

void setup() {
  Serial.begin(9600);
  Serial.println("0,0");
  //  pinMode(buzzer, OUTPUT);
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
  pinMode (led_red, OUTPUT);
  pinMode(led_blue, OUTPUT);
  pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT


}

void loop() {

  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);

  // Calculating the distance
  distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)

  int constrained_distance = constrain(distance, 0, 30); //constraining distance to be detected
  int mapped_distance = map(constrained_distance, 0, 30, 0, 1300); // mapping the values as per convinience 

  int light = analogRead(photo); // reading values from photoresistor
  int mapped_light = map(light, 0, 1023, 0, 10); //mapping the values from photoresistor as per convinience 
  int constrained_light = constrain(light, 900, 1000);
  
  int value = 0;
  int numReadings = 10;

  for (int i = 0; i < numReadings; i++) {
    value = value + mapped_distance;
    delay(1);
  }

  int selected_value = value / numReadings; //taking avg of numbers in group of 10
  int avg_value = selected_value / 4; //taking average of the above number 

  //establishing communication between processing and arduino

  while (Serial.available()) {
    right = Serial.parseInt();
    left = Serial.parseInt();
    if (Serial.read() == '\n') {
        
      Serial.print(avg_value);
      Serial.print(",");
      Serial.println(mapped_light);
     
    }
  }

  //condition for led lights to switch on and off
  if (mapped_light <= 5) {
    digitalWrite(led_red, HIGH); // turn the LED on
    digitalWrite(led_blue, LOW);
  } else {
    digitalWrite(led_red, LOW); // otherwise turn it off
    digitalWrite(led_blue, HIGH);
  }
}
}

Processing: 

import processing.serial.*;
import processing.sound.*;

Serial myPort;
SoundFile shoot;
SoundFile crash;
PImage ship;

int xPos=width/2;
int yPos=0;
float Ship;

ArrayList<Star> stars = new ArrayList<Star>(); //array for stars
int frequency = 4; //frequency of star


ArrayList<Asteroid> asteroids = new ArrayList<Asteroid>(); //array for asteroid
int asteroidFrequency = 25; //frequency of ateroid

ArrayList<Bullet> bullets = new ArrayList<Bullet>(); //array for bullets

int points;
boolean instruct = true;

EndScene end;

void setup() {
  //establishing connection with Arduino
  String portname=Serial.list()[4];
  //println(portname);
  myPort = new Serial(this, portname, 9600);
  myPort.clear();
  myPort.bufferUntil('\n');
  fullScreen();
  points = 0;
  ship = loadImage("spaceplane.png"); //loading image
  shoot = new SoundFile(this, "lazershoot_sound.wav");// shoot sound
  crash = new SoundFile(this, "space_crash.mp3");//crash sound
}

void draw() {

  if (end != null) {
    end.drawEndScene();
  } else {

    background(0);
    drawStar();

    serialEvent(myPort);
    fill(255);
    image(ship, xPos, height - height/4, 200, 100);
    drawBullet();
    if (instruct == true) {
      StartScene();
    } else {
      drawAsteroid();
      fill(255, 0, 0);
      stroke(255);



      stroke(255);
      fill(255);
      textSize(30);
      text("Points: " + points, 50, 50);

      checkCollision();
    }
  }
}


void drawBullet() {
  for (int i = 0; i<bullets.size(); i++) {
    bullets.get(i).drawBullet();
  }
}

void checkCollision() {
  for (int i = 0; i < asteroids.size(); i++) {
    Asteroid a = asteroids.get(i);
    float tan_shoot =  10*tan(60);
    float distance_ship= dist(a.x, a.y, xPos, (height-height/4)-tan_shoot);
    float distance_shipleft= dist(a.x, a.y, xPos+200, (height-height/4)+tan_shoot);
    if (distance_ship< a.size/2 +tan_shoot) {
      crash.play();
      end = new EndScene();
    }
    if (distance_shipleft<a.size/2+tan_shoot){
      crash.play();
      end = new EndScene();
    }
    for (int b = 0; b < bullets.size(); b++) {
      Bullet bullet = bullets.get(b);
      if (a.checkCollision(bullet) == true) {
        points++;

        asteroids.remove(a);
        bullets.remove(b);
      }
    }
  }
}


void drawAsteroid() {
  if (frameCount % asteroidFrequency == 0) {
    asteroids.add(new Asteroid(random(100, 250)));
  }
  for (int i = 0; i<asteroids.size(); i++) {
    Asteroid currentAsteroid = asteroids.get(i);
    currentAsteroid.drawAsteroid();
    if (currentAsteroid.y > height + currentAsteroid.size) {
      asteroids.remove(currentAsteroid);
      i--;
      points--;
    }
  }
}

void drawStar() {
  strokeWeight(1);
  stroke(255);
  if (frameCount % frequency == 0) {
    Star myStar = new Star();
    stars.add(myStar);
  }
  for (int i = 0; i<stars.size(); i++) {
    Star currentStar = stars.get(i);
    currentStar.drawStar();
  }
}

void serialEvent(Serial myPort) {
  loop();
  //frameRate(10);
  String s=myPort.readStringUntil('\n');
  s=trim(s);
  if (s!=null) {
    println(s);
    int values[]=int(split(s, ','));
    if (values.length==2 ) {
      //if (values[0]>=0) {
      xPos=(int)map(values[0], 0, 325, 0, width);
      //println(values[0]);
      println(xPos);
      if (xPos < 0) {
        xPos = 0;
        //}
      }
      if (xPos > width) {
        xPos = width;
      }
    }

    if ( values[1] <= 5) {
      Bullet b = new Bullet();
      bullets.add(b);
      shoot.amp(0.4);
      //shoot.play();
    }
  }
  myPort.write("0"+"\n");
}


void mousePressed() {
  if (end != null && end.mouseOverButton() == true) {
    resetGame();
  }
}

void resetGame() {
  instruct= true; 
  stars.clear();
  bullets.clear();
  asteroids.clear();
  end = null;
  points = 0;
}

void StartScene() {
  strokeWeight(7);
  stroke(0);
  fill(255);
  textSize(30);
  textAlign(CENTER);
  text("Try to move you hand within the taped area on the table", width/2, height/2-100);
  text(" Try opening and closing your hand completely to shoot bullets", width/2, height/2);
  text("PRESS SHIFT TO PLAY", width/2, height/2+100);
  if (keyPressed) {
    if (keyCode == SHIFT) {
      instruct = false;
    }
  }
}


class Asteroid {
  float size;
  float x;
  float y;
  int num;

  int speed_asteroid = 10; //speed of asteroid

  Asteroid(float size) {
    this.size = size;
    this.x = random(width);
    this.y = 0;
  }

  void drawAsteroid() {
    fill(150);
    stroke(150);
    ellipse(x, y, size, size);
    y+=speed_asteroid;
  }

  boolean checkCollision( Object crash) {
    if (crash instanceof Bullet) {
      Bullet bullet = (Bullet) crash;
      float distance_bullet = dist(x, y, bullet.x, bullet.y);
      if (distance_bullet <= size + bullet.size/2 ) {
        //fill(0, 255, 0, 100);
        //rect(0, 0, width, height);
        fill(255);

        return true;
      }
    }
    return false;
  }
}


class Bullet {
  float x;
  float y;
  float velocity_y;
  float size;

  Bullet() {
    this.x = xPos;
    this.y = (height-height/4) - 15;
    this.velocity_y = -10;
    this.size = 10;
  }

  void drawBullet() {
    fill(255);
    ellipse(x+100, y, size, size);
    y +=velocity_y;
    
  }
}


class EndScene {
  int button_x;
  int button_y; 
  int button_width; 
  int button_height;


  EndScene() {
    this.button_width = 300;
    this.button_height = 100;
    this.button_x = width/2 - this.button_width/2;
    this.button_y = height/2 - this.button_height/2;
  }

  void drawEndScene() {
    //Background
    fill(#FAE714);
    rect(0, 0, width, height);
    rect(button_x, button_y, button_width, button_height);

    //Game over text
    stroke(0);
    fill(0);
    textSize(150);
    textAlign(CENTER);
    text("GAME OVER!", width/2, height/4);

    //Restart Button
    fill(0);
    stroke(200);
    rect(button_x, button_y, button_width, button_height);
    fill(200);
    textSize(60);
    textAlign(CENTER); 
    text("RETRY?", button_x+150, button_y+70);
    
    //Player Score 
    stroke(0);
    fill(0);
    textSize(80);
    textAlign(CENTER); 
    text("FINAL SCORE: " + points, width/2, height - height/4);
  }

  boolean mouseOverButton() {
    return (mouseX > button_x 
      && mouseX < button_x + button_width
      && mouseY > button_y
      && mouseY < button_y + button_height);
  }
}


class Star {
  float x;
  float y;
  int velocity_star;
  
  Star() { 
    this.x = random(width);
    this.y = 0;
    this.velocity_star = 10; //velocity of falling star
  }
  
  void drawStar() {
    y+=velocity_star;
    fill(#FCEB24);
    circle(x,y,5);
  }
}

 

Final Project- Game: Space Survivor 🚀💫 [STATUS-90%]


Description of Project: 

Create a physically interactive system of your choice that relies on a multimedia computer for some sort of processing or data analysis. The Final should use BOTH Processing AND Arduino.Your focus should be on careful and timely sensing of the relevant actions of the person or people that you’re designing this for, and on clear, prompt, and effective responses. Any interactive system is going to involve systems of listening, thinking, and speaking from both parties. Whether it involves one cycle or many, the exchange should be engaging. You may work alone or in pairs.

Description of the game:

It is a space shooter game where there are spaceship has to protect itself from asteroids by either passing it by from a distance or by shooting it down. Each asteroid shot down is one point and to let  the asteroid  pass by is a negative point. As soon as your space ship crashes into an asteroid, the game is over and your final point are displayed on the screen.

Instead of a usual control as by a keyboard, this game is controlled by the movements of your hand. Using an ultrasonic sensor, the game using the distance between the the sensor and your hand, moves the spaceship along. A photo resistor is also installed in the glove, whose readings I have mapped from 0 to 10 and divided it in half, to help the with the shooting of the bullets by the player. Two led lights (red and blue) indicate if the shooting is taking place or no. Here’s a picture of the setup:

Here you can notice that the photo resistor is placed on the index  finger to give the player a better control to the shooting. all they have to do is close their finger or the entire hand, whatever is comfortable to them.

USER TESTING: 

Video: 

Feedback: 

  • ” You should add an instructions panel at the start of the game for the glove usage” –  I think that is a good idea and I will imply it next.
  • ” You should add sound” – This too I will imply next.
  • “The glove is not the most flexible with different hand sizes, maybe you can use disposable gloves and attach the sensor each time. It will also be easy to wear.” – I am not sure about the disposable gloves because it will create too much unnecessary waste, but I do agree with different hand sizes. I will try getting Professor’s take on this.

Next steps:

I will implement the above given suggestions and also work on the serial communication part of the game. I believe this game can be more smooth than what it is right now.

CODE:

processing:

import processing.serial.*;
Serial myPort;

int yPos=0;

ArrayList<Star> stars = new ArrayList<Star>();
int frequency = 4; //frequency of star

Ship playerShip;

ArrayList<Asteroid> asteroids = new ArrayList<Asteroid>();
int asteroidFrequency = 60;

ArrayList<Bullet> bullets = new ArrayList<Bullet>();

int points;

EndScene end;

void setup() {
  printArray(Serial.list());
  String portname=Serial.list()[4];
  println(portname);
  myPort = new Serial(this, portname, 9600);
  myPort.clear();
  myPort.bufferUntil('\n');
  fullScreen();
  playerShip = new Ship();
  points = 0;
}

void draw() {


  if (end != null) {
    end.drawEndScene();
  } else {
    background(0);
    drawStar();

    drawAsteroid();
    fill(255, 0, 0);
    stroke(255);
    playerShip.drawShip(myPort);
    drawBullet();
    

    stroke(255);
    fill(255);
    textSize(30);
    text("Points: " + points, 50, 50);

    checkCollision();
  }
}

void drawBullet() {
  serialBullet(myPort);
  for (int i = 0; i<bullets.size(); i++) {
    bullets.get(i).drawBullet();
  }
}

void checkCollision() {
  for (int i = 0; i < asteroids.size(); i++) {
    Asteroid a = asteroids.get(i);
    if (a.checkCollision(playerShip) == true) {
      end = new EndScene();
    }
    for (int b = 0; b < bullets.size(); b++) {
      Bullet bullet = bullets.get(b);
      if (a.checkCollision(bullet) == true) {
        points++;

        asteroids.remove(a);
        bullets.remove(b);
      }
    }
  }
}


void drawAsteroid() {
  if (frameCount % asteroidFrequency == 0) {
    asteroids.add(new Asteroid(random(100, 250)));
  }
  for (int i = 0; i<asteroids.size(); i++) {
    Asteroid currentAsteroid = asteroids.get(i);
    currentAsteroid.drawAsteroid();
    if (currentAsteroid.y > height + currentAsteroid.size) {
      asteroids.remove(currentAsteroid);
      i--;
      points--;
    }
  }
}

void drawStar() {
  strokeWeight(1);
  stroke(255);
  if (frameCount % frequency == 0) {
    Star myStar = new Star();
    stars.add(myStar);
  }
  for (int i = 0; i<stars.size(); i++) {
    Star currentStar = stars.get(i);
    currentStar.drawStar();
  }
}

void serialBullet(Serial myPort) {
  String s=myPort.readStringUntil('\n');
  s=trim(s);
  if (s!=null) {
    println(s);
    int values[]=int(split(s, ','));
    if (values.length==2 && values[1] <= 5) {
      Bullet b = new Bullet(playerShip);
      bullets.add(b);
    }
  }
}

    void mousePressed() {
      if (end != null && end.mouseOverButton() == true) {
        resetGame();
      }
    }

    void resetGame() {
      stars.clear();
      bullets.clear();
      asteroids.clear();
      playerShip = new Ship();
      end = null;
      points = 0;
    }

class Asteroid {
  float size;
  float x;
  float y;
  int num;

  int speed_asteroid = 5; //speed of asteroid

  Asteroid(float size) {
    this.size = size;
    this.x = random(width);
    this.y = 0;
  }

  void drawAsteroid() {
    fill(150);
    stroke(150);
    ellipse(x, y, size, size);
    y+=speed_asteroid;
  }

  boolean checkCollision( Object crash) {
    if (crash instanceof Ship) {
      Ship playerShip = (Ship) crash;
      float tan_shoot =  10*tan(60);
      float distance_ship= dist(x, y, playerShip.xPos, playerShip.y-tan_shoot);
      if (distance_ship< size/2 +tan_shoot){ //tan_shoot+ 10) {
        //background(255, 0, 0);
        fill(255, 0, 0, 100);
        rect(0, 0, width, height);
        fill(255);
        
        return true;
      }
    } else if (crash instanceof Bullet) {
      Bullet bullet = (Bullet) crash;
      float distance_bullet = dist(x, y, bullet.x, bullet.y); 
      //println(distance_bullet);
      if (distance_bullet <= size + bullet.size/2 ) {
        fill(0, 255, 0, 100);
        rect(0, 0, width, height);
        fill(255);
        
        return true;
      }
    }
    return false;
    
  }
}

class Bullet {
  float x;
  float y;
  float velocity_y;
  float size; 

  Bullet(Ship playerShip) {
    this.x = playerShip.xPos;
    this.y = playerShip.y - 15;
    this.velocity_y = -10;
    this.size = 10;
  }

  void drawBullet() {
        fill(255);
        ellipse(x+100, y, size, size);
        y +=velocity_y;
      }
}

class EndScene {
  int button_x;
  int button_y; 
  int button_width; 
  int button_height;


  EndScene() {
    this.button_width = 300;
    this.button_height = 100;
    this.button_x = width/2 - this.button_width/2;
    this.button_y = height/2 - this.button_height/2;
  }

  void drawEndScene() {
    //Background
    fill(#FAE714);
    rect(0, 0, width, height);
    rect(button_x, button_y, button_width, button_height);

    //Game over text
    stroke(0);
    fill(0);
    textSize(150);
    textAlign(CENTER);
    text("GAME OVER!", width/2, height/4);

    //Restart Button
    fill(0);
    stroke(200);
    rect(button_x, button_y, button_width, button_height);
    fill(200);
    textSize(60);
    textAlign(CENTER); 
    text("RETRY?", button_x+150, button_y+70);
    
    //Player Score 
    stroke(0);
    fill(0);
    textSize(80);
    textAlign(CENTER); 
    text("FINAL SCORE: " + points, width/2, height - height/4);
  }

  boolean mouseOverButton() {
    return (mouseX > button_x 
      && mouseX < button_x + button_width
      && mouseY > button_y
      && mouseY < button_y + button_height);
  }
}

class Ship {
  PImage ship;
  float x;
  float y;
  float velocity_x;
  boolean leftPressed, rightPressed;
  int xPos=0;

  int speed = 6; //speed of ship

  Ship() {
    this.x = width/2;
    this.y = height - height/4;
    this.velocity_x = 0;
    ship = loadImage("spaceplane.png");
  }

  void drawShip(Serial myPort) {
    frameRate(60);
    String s=myPort.readStringUntil('\n');
    s=trim(s);
    if (s!=null) {
      println(s);
      int values[]=int(split(s, ','));
      if (values.length==2) {
        xPos=(int)map(values[0], 0, 30, 0, width);
        image(ship, xPos, y);
        ship.resize(200, 100);
      }
    }
  }
}

class Star {
  float x;
  float y;
  int velocity_star;
  
  Star() { 
    this.x = random(width);
    this.y = 0;
    this.velocity_star = 10; //velocity of falling star
  }
  
  void drawStar() {
    y+=velocity_star;
    fill(#FCEB24);
    circle(x,y,5);
  }
}

Arduino:

int left = 0; 
int right = 0; 

const int echoPin = 2;  // attach pin D2 Arduino to pin Echo of HC-SR04
const int trigPin = 3; //attach pin D3 Arduino to pin Trig of HC-SR04
const int led_red = 9;
const int led_blue = 8;
const int photo = A0;


// defines variables
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement

void setup() {
  Serial.begin(9600); 
  Serial.println("0,0");
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
  pinMode (led_red, OUTPUT);
  pinMode(led_blue, OUTPUT);
  pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
   
  
}
void loop() {
  while (Serial.available()){
    right = Serial.parseInt();
    left = Serial.parseInt(); 
  }

  digitalWrite(trigPin, LOW);
  digitalWrite(trigPin, HIGH);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);

  // Calculating the distance
  distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (going and coming)
  int constrained_distance = constrain(distance, 0, 30);
  
  int light = analogRead(photo);
  int mapped_light = map(light, 0, 1023, 0, 10);
  int constrained_light = constrain(light, 900, 1000);

  if (mapped_light <= 5) {
    digitalWrite(led_red, HIGH);
    digitalWrite(led_blue, LOW);
  } else {
    digitalWrite(led_red, LOW);
    digitalWrite(led_blue, HIGH);
  }
  Serial.print(constrained_distance); 
  Serial.print(","); 
  Serial.println(mapped_light); 
  delayMicroseconds(100);
}

 

Week 12 Final Project: Space Tour :) 🚀

Project Description: 

After giving it much thought, I have decided to make my final project on an arcade game the space shooter game such as this one:

However, I would like to bring my own twist to it by making in a way that it is controlled by your motion and instead of the usual gaming controls. I plan on using a pair of latex gloves with photoresistor sensors to control the  different type of shootings in the game and the ultrasonic sensors to detect the motion of the players. I also plan on using the potentiometer to set the level of difficulty (easy/medium/hard) by dividing the input into 3 intervals.

The players will also have lives on the top corner to make it a little more challenging and the opponents for the player will keep changing between alien ships and asteroids with different powers to keep it interesting.

Requirements:

  • Ultrasonic sensors x2
  • photoresistors x3
  • led lights x3
  • potentiometer x1
  • Breadboard and Arduino x1
  • gloves x1 pair
  • jumper and cable wires
  • Aluminium tape

As of now I am working on the game and structure it in a way where it would be easy for me to connect it with the Arduino later. I believe connecting it with Arduino is going to be the toughest part since I believe I have not had enough practice to polish my serial communication skills between Arduino and Processing.

Hence side by side, I am also planning to give enough time to Arduino with a demo programme to see how to go about it.

Final Project Proposal: motion induced gaming

Description: 

Create a physically interactive system of your choice that relies on a multimedia computer for some sort of processing or data analysis. The Final should use BOTH Processing AND Arduino.Your focus should be on careful and timely sensing of the relevant actions of the person or people that you’re designing this for, and on clear, prompt, and effective responses. Any interactive system is going to involve systems of listening, thinking, and speaking from both parties. Whether it involves one cycle or many, the exchange should be engaging. You may work alone or in pairs.

Idea: 

I plan on creating a video game influenced by your hand moments using a glove. So the character in the game would be guided by different sensors on the gloves and move around accordingly. 

Processing: 

This will the area of display for the game. I am imagining creating a game something like Mario, which includes jumping and moving forward. In addition to that maybe I can get some enemies and some fighting as well. 

Arduino: 

Photoresistors , potentiometers, buzzer, and ultrasonic sensors are some of the things I plan on using on the technical part. I have not decided which sensor will help me for what function, but I am sure it is going to be something along these lines. 

Week 11: Communication Exercise

DESCRIPTION: 

  1. make something that uses only one sensor  on arduino and makes the ellipse in processing move on the horizontal axis, in the middle of the screen, and nothing on arduino is controlled by processing
  2. make something that controls the LED brightness from processing
  3. take the gravity wind example

GIVEN CODE: 

int left = 0;
int right = 0;

void setup() {
  Serial.begin(9600);
  Serial.println("0,0");
  pinMode(2, OUTPUT);
  pinMode(5, OUTPUT);
}

void loop() {
  while (Serial.available()) {
    right = Serial.parseInt();
    left = Serial.parseInt();
    if (Serial.read() == '\n') {
      digitalWrite(2, right);
      digitalWrite(5, left);
      int sensor = analogRead(A0);
      delay(1);
      int sensor2 = analogRead(A1);
      delay(1);
      Serial.print(sensor);
      Serial.print(',');
      Serial.println(sensor2);
    }
  }
}

/*

import processing.serial.*;
Serial myPort;
int xPos=0;
int yPos=0;
boolean onOff=false;
boolean onOff2=false;

void setup(){
  size(960,720);
  printArray(Serial.list());
  String portname=Serial.list()[1];
  println(portname);
  myPort = new Serial(this,portname,9600);
  myPort.clear();
  myPort.bufferUntil('\n');
}

void draw(){
  background(255);
  ellipse(xPos,yPos,30,30);
  if (mousePressed){
    if(mouseX<=width/2)
      onOff2=true;
    else
      onOff=true;
  }else{
    onOff=onOff2=false;
  }
}

void serialEvent(Serial myPort){
  String s=myPort.readStringUntil('\n');
  s=trim(s);
  if (s!=null){
    println(s);
    int values[]=int(split(s,','));
    if (values.length==2){
      xPos=(int)map(values[0],0,1023,0, width);
      yPos=(int)map(values[1],0,1023,0, height);
    }
  }
  myPort.write(int(onOff)+","+int(onOff2)+"\n");
}

 */

EXERCISE 1: 

int left = 0;
int right = 0;

void setup() {
 Serial.begin(9600);
 Serial.println("0,0");
 pinMode(2, OUTPUT);
 pinMode(5, OUTPUT);
}

void loop() {
 while (Serial.available()) {
   right = Serial.parseInt();
   left = Serial.parseInt();
   if (Serial.read() == '\n') {
     digitalWrite(2, right);
     digitalWrite(5, left);
     int sensor = analogRead(A0);
     delay(1);
     int sensor2 = analogRead(A1);
     delay(1);
     Serial.print(sensor);
     Serial.print(',');
     Serial.println(sensor2);
   }
 }
}


//////////////////////////////////////////////////////

import processing.serial.*;
Serial myPort;
int xPos=0;
//int yPos=0;
boolean onOff=false;
boolean onOff2=false;

void setup(){
 size(960,720);
 printArray(Serial.list());
 String portname=Serial.list()[4];
 println(portname);
 myPort = new Serial(this,portname,9600);
 myPort.clear();
 myPort.bufferUntil('\n');
}

void draw(){
 background(255);
 ellipse(xPos,height/2,30,30);
 //if (mousePressed){
 //  if(mouseX<=width/2)
 //    onOff2=true;
 //  else
 //    onOff=true;
 //}else{
 //  onOff=onOff2=false;
 //}
}

void serialEvent(Serial myPort){
 String s=myPort.readStringUntil('\n');
 s=trim(s);
 if (s!=null){
   println(s);
   int values[]=int(split(s,','));
   if (values.length==2){
     xPos=(int)map(values[0],0,1023,0, width);
     //yPos=(int)map(values[1],0,1023,0, height);
   }
 }
 myPort.write(int(onOff)+","+int(onOff2)+"\n");
}

EXERCISE 2: 

import processing.serial.*;
Serial myPort;
//int xPos=0;
int yPos=0;
float brightness;
//boolean onOff=false;
//boolean onOff2=false;

void setup(){
 size(960,720);
 printArray(Serial.list());
 String portname=Serial.list()[4];
 println(portname);
 myPort = new Serial(this,portname,9600);
 myPort.clear();
 myPort.bufferUntil('\n');
}

void draw(){
 background(255);
 ellipse(width/2,mouseY,30,30);
 brightness = map(mouseY,0,height,0,255);
 myPort.write(int(brightness)+ "\n"); 
 //if (mousePressed){
 //  if(mouseX<=width/2)
 //    onOff2=true;
 //  else
 //    onOff=true;
 //}else{
 //  onOff=onOff2=false;
 //}
}

//void serialEvent(Serial myPort){

//  String s=myPort.readStringUntil('\n');

//  s=trim(s);
//  //if (s!=null){
//  //  println(s);
//    //int values[]=int(split(s,','));

//    //if (values.length==2){
//    //  //xPos=(int)map(values[0],0,1023,0, width);
//    //  yPos=(int)map(values[1],0,1023,0, height);
//   // }
//  //}
//  //myPort.write(int(onOff)+","+int(onOff2)+"\n");

//}


//////////////////////////////////////////////

//int left = 0;
//int right = 0;
int brightness;

void setup() {
 Serial.begin(9600);
 Serial.println("0");
 pinMode(3, OUTPUT);
 //  pinMode(5, OUTPUT);
}

void loop() {
 while (Serial.available()) {
   brightness = Serial.parseInt();
   //left = Serial.parseInt();
   if (Serial.read() == '\n') {
     analogWrite(3, brightness);
     //digitalWrite(5, left);
     //      int sensor = analogRead(A0);
     //      delay(1);
     //      int sensor2 = analogRead(A1);
     //      delay(1);
     //      Serial.print(sensor);
     //      Serial.print(',');
     //      Serial.println(sensor2);
   }
 }
}

EXERCISE 3

int onoff;
void setup() {
  Serial.begin(9600);
  Serial.println("0");
  pinMode(5, OUTPUT);
}
void loop() {
  while (Serial.available()) {
    onoff = Serial.parseInt();
    if (Serial.read() == '\n') {
      digitalWrite(5, onoff);
      int sensor = analogRead(A0);
      delay(1);
      Serial.println(sensor);
    }
  }
}


/////////////////////////////////////////////////////////////

import processing.serial.*;
Serial myPort;
PVector velocity;
PVector gravity;
PVector position;
PVector acceleration;
PVector wind;
float drag = 0.99;
float mass = 50;
float hDampening;
float windcontrolled;
boolean onoff = false;
void setup() {
  size(640,360);
  noFill();
  position = new PVector(width/2, 0);
  velocity = new PVector(0,0);
  acceleration = new PVector(0,0);
  gravity = new PVector(0, 0.5*mass);
  wind = new PVector(0,0);
  hDampening=map(mass,15,80,.98,.96);
  
  //port communication
  printArray(Serial.list());
  String portname=Serial.list()[4];
  println(portname);
  myPort = new Serial(this,portname,9600);
}
void draw() {
  background(255);
  if (!keyPressed){
    wind.x=windcontrolled;
    velocity.x*=hDampening;
  }
  applyForce(wind);
  applyForce(gravity);
  velocity.add(acceleration);
  velocity.mult(drag);
  position.add(velocity);
  acceleration.mult(0);
  ellipse(position.x,position.y,mass,mass);
  if (position.y > height-mass/2) {
      velocity.y *= -0.9;  // A little dampening when hitting the bottom
      position.y = height-mass/2;
  }
  if (position.y >= height-mass) {
      onoff = true;
  }
  else{
    onoff=false;
  }
  
}
void serialEvent(Serial myPort){
  String s=myPort.readStringUntil('\n');
  s=trim(s);
  if (s!=null){
    int value = parseInt(s);
    windcontrolled = map(value,0,1023,-1, 1);
  }
  myPort.write(int(onoff)+"\n");
}
  
void applyForce(PVector force){
  // Newton's 2nd law: F = M * A
  // or A = F / M
  PVector f = PVector.div(force, mass);
  acceleration.add(f);
}
void keyPressed(){
  if (keyCode==LEFT){
    wind.x=-1;
  }
  if (keyCode==RIGHT){
    wind.x=1;
  }
  if (key==' '){
    mass=random(15,80);
    position.y=-mass;
    velocity.mult(0);
  }
}

VIDEO OF EXERCISE 3: 

 

Musical Instrument: Shanaia Paruthi & Fatima Nadeem

Description 

In pairs, make a musical instrument

  • You must use at least one digital sensor (switch)
  • You must use at least one analog sensor (photoresistor, potentiometer, or distance measuring sensor)

Process: 

What if you could play music without even touching the instrument!

So our device uses a photoresistor to detect the amount of light around the system and uses that light to give different frequencies out of the buzzer to create a musical tone with some LED effect.

We started off with building a circuit for the photoresistor to detect the amount of light around the system. Then we divided that value into 5 different intervals for the LED. in each interval, a single led lights up indicating  the note. We did the same  with the buzzer.  In the end, we added a switch to keep the device from switching on/off. Here’s a picture of our system:

So the current in the system first goes to the photoresistor to detect the light, which is mapped for the buzzer frequency (note), the led lights, and the duration of the notes. Which ultimately gets displayed as below:

VIDEO:

CODE:

#include "pitches.h"

//creating an array for the noted used
int notes[10] = {NOTE_C4, NOTE_D4, NOTE_E4, NOTE_F4, NOTE_G4, NOTE_A4, NOTE_B4, NOTE_C5, NOTE_D5, NOTE_E5};

//declaring the ports 
const int button = 13;
int const red1 = 2;
int const yellow = 7;
int const blue = 4;
int const green = 8;
int const red2 = 12;
const int tonepin = 5;
const int photoresistor = A0;

//creating an array for the lights with respect to leds
int lights[5] = {2, 4, 7, 8, 12};

//declaring the original state
bool lastButtonState = LOW;
bool onoff = LOW;


void setup() {

  //starting the sensors 
  Serial.begin(9600);
 
  //declaring the function of the port
  pinMode(red1, OUTPUT);
  pinMode(blue, OUTPUT);
  pinMode(red2, OUTPUT);
  pinMode(green, OUTPUT);
  pinMode(yellow, OUTPUT);
  pinMode(tonepin, OUTPUT);
  pinMode(button, INPUT);

}

void loop() {

  bool buttonState = digitalRead(button);//reaing the state
  Serial.println(buttonState);

  //condition for button
  if (buttonState != lastButtonState) {
    if (buttonState == LOW) {
      onoff = (onoff == HIGH) ? LOW: HIGH;
    }
  }
  lastButtonState = buttonState;
  if(onoff==HIGH){
    for (int light = 0; light < 5; light++) { //loop for lights 
      digitalWrite(lights[light], LOW);
    }
    int value = analogRead(photoresistor); //reading photoresistor
 
    //mapping the values
    int mappedValue = map(value, 0, 900, 100, 150);
    int mappedValue2 = map(value, 0, 900, 0, 9);
    int mappedValue3 = map(value, 0, 900, 0, 4);

    //condition for the buzzer
    if (millis() % mappedValue == 0) {
      tone(tonepin, notes[mappedValue2], mappedValue);
    }
    digitalWrite(lights[mappedValue3], HIGH);
  }
  
}



////////////////////////////////////////////////////


/*************************************************

 * Public Constants

 *************************************************/

#define NOTE_B0  31
#define NOTE_C1  33
#define NOTE_CS1 35
#define NOTE_D1  37
#define NOTE_DS1 39
#define NOTE_E1  41
#define NOTE_F1  44
#define NOTE_FS1 46
#define NOTE_G1  49
#define NOTE_GS1 52
#define NOTE_A1  55
#define NOTE_AS1 58
#define NOTE_B1  62
#define NOTE_C2  65
#define NOTE_CS2 69
#define NOTE_D2  73
#define NOTE_DS2 78
#define NOTE_E2  82
#define NOTE_F2  87
#define NOTE_FS2 93
#define NOTE_G2  98
#define NOTE_GS2 104
#define NOTE_A2  110
#define NOTE_AS2 117
#define NOTE_B2  123
#define NOTE_C3  131
#define NOTE_CS3 139
#define NOTE_D3  147
#define NOTE_DS3 156
#define NOTE_E3  165
#define NOTE_F3  175
#define NOTE_FS3 185
#define NOTE_G3  196
#define NOTE_GS3 208
#define NOTE_A3  220
#define NOTE_AS3 233
#define NOTE_B3  247
#define NOTE_C4  262
#define NOTE_CS4 277
#define NOTE_D4  294
#define NOTE_DS4 311
#define NOTE_E4  330
#define NOTE_F4  349
#define NOTE_FS4 370
#define NOTE_G4  392
#define NOTE_GS4 415
#define NOTE_A4  440
#define NOTE_AS4 466
#define NOTE_B4  494
#define NOTE_C5  523
#define NOTE_CS5 554
#define NOTE_D5  587
#define NOTE_DS5 622
#define NOTE_E5  659
#define NOTE_F5  698
#define NOTE_FS5 740
#define NOTE_G5  784
#define NOTE_GS5 831
#define NOTE_A5  880
#define NOTE_AS5 932
#define NOTE_B5  988
#define NOTE_C6  1047
#define NOTE_CS6 1109
#define NOTE_D6  1175
#define NOTE_DS6 1245
#define NOTE_E6  1319
#define NOTE_F6  1397
#define NOTE_FS6 1480
#define NOTE_G6  1568
#define NOTE_GS6 1661
#define NOTE_A6  1760
#define NOTE_AS6 1865
#define NOTE_B6  1976
#define NOTE_C7  2093
#define NOTE_CS7 2217
#define NOTE_D7  2349
#define NOTE_DS7 2489
#define NOTE_E7  2637
#define NOTE_F7  2794
#define NOTE_FS7 2960
#define NOTE_G7  3136
#define NOTE_GS7 3322
#define NOTE_A7  3520
#define NOTE_AS7 3729
#define NOTE_B7  3951
#define NOTE_C8  4186
#define NOTE_CS8 4435
#define NOTE_D8  4699
#define NOTE_DS8 4978

 

Week 9: Night Musical Box!

Description 

Get information from at least one analog sensor and at least one digital sensor (switch), and use this information to control at least two LEDs, one in a digital fashion and the other in an analog fashion, in some creative way.

Process

I started with creating a box out of the cardboard, with holes on the top for the lights. Using the light sensor , I detected when the lights were out and only when it was dark would the potentiometer (knob) get power from its port, and transfer it current to different leds and the buzzer. I used 330 ohm resistor for each leds, and 10k resistor for the light sensor and the buzzer.  Here is a photo of the setup:

The output of the knob is divided between three intervals. On each interval, one light lights up , starting with the yellow led and ending at the blue one.  The buzzer too at each interval beeps at different frequencies, giving a musical note.

Here’s a video:

CODE: 

//declaring the ports
const int pot_power = 2;
const int ledyellow = 3;
const int ledred = 5;
const int ledblue = 9;
const int buzzer = 11;
const int light = 13;
const int pot = A0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600); // begin detecting the sensors
  //declaring role of each port
  pinMode(pot_power, OUTPUT);
  pinMode(ledyellow, OUTPUT);
  pinMode(ledred, OUTPUT);
  pinMode(ledblue, OUTPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(light, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:

  int lightValue = digitalRead(light); //reading value from the light port


  if (lightValue = 1) { //condition
    digitalWrite(pot_power, HIGH);
  } else {
    digitalWrite(pot_power, LOW);
    noTone(buzzer);// switch off buzzer
  }
  delay (100);

  int potValue = analogRead(pot); // reading value of the dial
  int mappedValue = map(potValue, 0, 1023, 0, 255); //mapping it to a value compatible for LEDs
  //  Serial.println(lightValue);
  //  Serial.println(mappedValue);
  //condition
  if ( mappedValue < 85) {
    analogWrite(ledyellow, HIGH);
    analogWrite(ledred, LOW);
    analogWrite(ledblue, LOW);
    tone(buzzer, 1000);
  }
  if (mappedValue >= 85 && mappedValue < 170) {
    analogWrite(ledyellow, LOW);
    analogWrite(ledred, HIGH);
    analogWrite(ledblue, LOW);
    tone (buzzer, 1500);
  }
  if (mappedValue >= 170) {
    analogWrite(ledyellow, LOW);
    analogWrite(ledred, LOW);
    analogWrite(ledblue, HIGH);
    tone(buzzer, 2000);
  }
  delay(100);
}

 

Week 8: Bicep function detector :)

Description

Create an unusual switch that doesn’t require the use of your hands. Use Arduino digital input and output for the interaction.

Process

Do your biceps work? Let’s find out! This is a switch that works using the mechanisms of your elbow. As you close your elbow the switch shows a green light, and when open it shows a red one.

So the programme requires basic coding. I use two LED lights, one red and one green, and wires to connect the flow of electricity. Using cardboard, I created two patches each to be applied on either sides of the inner side of the elbow, and put wires on each side, one going for the output (5V port)  and one for the input and taped it around my arm.

Then creating the following code where if and only if the electricity is flowing through the wire will the lights turn green, otherwise red indicating if the elbow is closed or open. Hence, showing if your biceps are working in your body or not!

CODE:

//declaring the constant variables
const int redPin = 8;
const int book = 6;
const int greenPin = 3;
bool currentState = false;
bool bookState = LOW;

void setup() {
  //determining the source function
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(book, INPUT);
}

void loop() {
    bookState = digitalRead(book); //reading the input of book switch
    //condition to change the lights 
    if (currentState != bookState ){
      digitalWrite(greenPin, HIGH); //green on, red off
      digitalWrite(redPin, LOW);
     } else {
      digitalWrite(greenPin, LOW);//green off red on 
      digitalWrite(redPin, HIGH);
    }
}

VideoGame: Don’t Crash!

Description

For the midterm assignment, we were asked to make a video game using processing. I made one in which the person has to try crossing the road without getting hit by the car.

Process

I used basic shapes to create a scenario of a road on the screen. The roads are made out of the rectangles. The cars are made using the rectangle with curved edges and ellipses for wheels. Along with a sun in the corner.

So my game is quite simple. Using sprite sheet, I made a person move across the screen for the game.  The cars come from the side in random speeds to try and hit the person. The speed increases with increase in every level.

There are three levels in total and are shown in the top-left corner. When the bar goes all the way up to green, it means that the player has all three lives. On getting hit by the car,  a life is reduced and the player as to start the game all the way from the start of the road.

I have added sound to the game( which somehow does not come in the video below). The sounds add a a special affect to the game I believe.  The start of the game shows instructions on how to play the game. Just follow the simple instructions and win the game.

The player to cross all three rounds, wins the game. Here’s the video for the game:

 

CODE:

PFont intro;
PImage spritesheet;
PImage background_image;
PImage[][] sprites;
int direction = 1; // 0 up
int step = 0;
int x;
int y;
int speed = 3;
int level = 1;
float car1x = 750;
float hood1x = 720;
float wheel1a = 825;
float wheel1b = 775;
float car2x = -150;
float hood2x = -50;
float wheel2a = -130;
float wheel2b = -75;
float speed1 = 50;
float speed2= 50;
int lives = 3; 
import processing.sound.*;
SoundFile sound_cars;
SoundFile sound_levelup;
SoundFile sound_lost;
SoundFile sound_win;
SoundFile sound_crash;
boolean instruct = true; 


void setup() {
  size(600,600);
  background_image = loadImage("im_game.jpg"); //the background image
  spritesheet = loadImage("man_walking.png"); //the man
  sprites = new PImage[4][9]; //putting spritesheet in an array

  int w = spritesheet.width/9; 
  int h = spritesheet.height/4;

  for (int y=0; y < 4; y++) {
    for (int x=0; x< 9; x++) {
      sprites[y][x] = spritesheet.get(x*w, y*h, w, h);
    }
  }

  x = 300; // setting the original values
  y = 370;
  
  imageMode(CENTER);
  //introducing sound. 
  sound_cars = new SoundFile(this, "sound_cars.wav");
  sound_levelup = new SoundFile(this,"sound_levelup.wav");
  sound_lost= new SoundFile(this,"game_lost.mp3");
  sound_win = new SoundFile(this,"sound_win.wav");
  sound_crash = new SoundFile(this,"sound_crash.mp3");
  
  //playing the sound of cars
  if (level < 4 && lives > 0 ){
    sound_cars.loop();
  }
}

void draw() {
  //laying a base
  background(255,70);
  
  //displaying the image
  image(background_image,400,280);
  
  
  //showing the instructions
  instructions();
  
  if (instruct == false){
  lifeline(); ///showing the lifelines
  
  scene();//displaying the scene

  car1_dimension();//calling out the car1 dimensions
  
  car2_dimensions();//calling out the car2 dimensions

  
  //executing the game
  if (level == 1 && lives >0) {
    
  movecar1();
  
  if (car1x < 0){
    speed1 = random(5,10);
    car1x = 750;
    hood1x = 720;
    wheel1a = 825;
    wheel1b = 775;
  }
  
  movecar2();
  
  if (car2x > 600){
    speed2 = random(5,10);
    car2x = -150;
    hood2x = -50;
    wheel2a = -130;
    wheel2b = -75;
  }
  
  //Determining the direction of the man
  moveman();
  
  image(sprites[direction][step], x, y); //printing the image
  
  crash();//calling out the crash function
   
}

  if (level == 2 && lives >0 ){
    car1_dimension();
    
    movecar1();
    
    if (car1x < 0){
    speed1 = random(10,13);//speed upgrades with every level
    car1x = 750;
    hood1x = 720;
    wheel1a = 825;
    wheel1b = 775;
  }
  
  car2_dimensions();
  
  movecar2();
  
  if (car2x > 600){
    speed2 = random(10,13);
    car2x = -150;
    hood2x = -50;
    wheel2a = -130;
    wheel2b = -75;
  }
  
  //Determining the direction of the man
  moveman();

  image(sprites[direction][step], x, y); //printing the image
  crash();
}
  if (level == 3 && lives >0){
    
   car1_dimension();
   
   movecar1();
    
    if (car1x < 0){
    speed1 = random(13,17);
    car1x = 750;
    hood1x = 720;
    wheel1a = 825;
    wheel1b = 775;
  }
  
  car2_dimensions();
  
  movecar2();
  
  if (car2x > 600){
    speed2 = random(13,17);
    car2x = -150;
    hood2x = -50;
    wheel2a = -130;
    wheel2b = -75;
  }
  
  //Determining the direction of the man
  moveman();
  
  image(sprites[direction][step], x, y); //printing the image 
  
  crash();
  }
  
  //level up settings
  if (y>600){
    level+=1;
    sound_levelup.play(); //level up sound
    car1x = 750;
    hood1x = 720;
    wheel1a = 825;
    wheel1b = 775;
    car2x = -150;
    hood2x = -50;
    wheel2a = -130;
    wheel2b = -75;
    speed1 = 20;
    speed2= 20;
    x= 300;
    y= 370; 
    }
   if (y<370){
     y=370;
   }
   if (x<0){
     x=0;
   }
   if (x>600){
     x=600;
   }
   if (y>600){
    sound_levelup.play();
  }
     
  if (instruct == false){
  leveltext(); // to display level only on starting the game
  }
}
}


//function to indicate lives left
void lifeline(){
  
  if (lives == 3){
   //shows all three boxes
  fill(#F21D1D);
  rect(10,10,50,10);
  fill(#FACC12);
  rect(55,10,95,10);
  fill(#62E32C);
  rect(100,10,140,10);
  }
  if (lives ==2){
   //deleted the green box showing two lives left
  fill(#F21D1D);
  rect(10,10,50,10);
  fill(#FACC12);
  rect(55,10,95,10);
  }
  if (lives == 1){
  //deletes the orange box showing one life left
  fill(#F21D1D);
  rect(10,10,50,10);
  }
} 

void scene(){
  //background
  stroke(255,69,0);
  strokeWeight (3);
  
  stroke (1);
  strokeWeight (1);
  
  //road
  fill(100);
  rect(0,400,600,200);
  
  //road lines
  fill(255,255,0);
  rect(0,475,600,8);
  rect(0,517,600,8);
  
  //sun
  arc(600,0,200,200,radians(90),radians(180),PIE);
  }
  
void car1_dimension(){
  fill(0,191,255);
  rect(car1x,405,100,50,80,30,0,0);
  rect(hood1x,430,30,25,40,0,0,0);
  fill(1);
  ellipse(wheel1a,450,25,25);
  ellipse(wheel1b,450,25,25);
  }
  
void car2_dimensions(){
  fill(255,20,20);
  rect(car2x,535,100,50,30,80,0,0);
  rect(hood2x,560,30,25,0,40,0,0);
  fill(1);
  ellipse(wheel2a,580,25,25);
  ellipse(wheel2b,580,25,25);
}

void movecar1(){
  //subtracting speed to make the car move left
  car1x -=  speed1;
  hood1x -=  speed1;
  wheel1a -=  speed1;
  wheel1b -=  speed1;
}

void movecar2(){
  //adding speed to make the car move right
  car2x += speed2;
  hood2x += speed2;
  wheel2a += speed2;
  wheel2b += speed2;
}

//function to make the man move
void moveman(){
  if (keyPressed) {
    if (keyCode == DOWN) { //to move down
      direction = 2;
      y +=speed*0.6;
    }
    if (keyCode == LEFT) { //to move left
      direction = 1;
      x -=speed*0.6;
    }
    if (keyCode == RIGHT) { //to move right
      direction = 3;
      x +=speed*0.6;
    }
    if (keyCode == UP) { //to move up
      direction = 0;
      y -=speed*0.6;
    }
    if (frameCount%speed==0) { //repeating the spritesheet
      step = (step+1) % 9;
    }
  }  
}

//function to detect if the man crashes with the car
 void crash(){
  //calculating distance between man and the car
  float distancehood1 = dist(hood1x,430,x,y);
  float distancehood2 = dist(hood2x,560,x,y);
  float distancecar1 = dist(car1x,405,x,y);
  float distancecar2 = dist(car2x,535,x,y);
  float distancebody1 = dist(car1x + 30,405,x,y);
  float distancebody2 = dist(car2x + 30,405,x,y);
  //detecting a crash
  if (distancehood1 < 15){
  y = 370;// restarting man's position to the start of the road
  lives -=1;// reducing lives
  sound_crash.play(); //playing sound
}
  if (distancehood2 < 15){
  y = 370;// restarting man's position to the start of the road
  lives-=1; // reducing lives
  sound_crash.play(); //playing sound
}
  if (distancecar1 < 15){
  y = 370; // restarting man's position to the start of the road
  lives -=1; // reducing lives
  sound_crash.play(); //playing sound
}
  if (distancecar2 < 15){
  y = 370; // restarting man's position to the start of the road
  lives -=1; // reducing lives
  sound_crash.play(); //playing sound
}
  if (distancebody1 < 15){
  y = 370; // restarting man's position to the start of the road
  lives -=1; // reducing lives
  sound_crash.play(); //playing sound
}
  if (distancebody2 < 15){
  y = 370; // restarting man's position to the start of the road
  lives-=1; // reducing lives
  sound_crash.play(); //playing sound
}
  }

//displaying level of the game
void leveltext(){
  if (level == 4 && lives >0){
    background(0);
    
    textSize(50);
    fill(255);
    text("Congratulations! \n You Win!!",150,200);
    sound_cars.stop();
  }
  
  if (level == 1 && lives >0 || level == 2 && lives >0 || level == 3 && lives >0){
  textSize(100);
  fill(#1AD628);
  textAlign(CENTER);
  text(level,278,100);
  }
  
  if (lives == 0){
    background(0);
    textSize(60);
    fill(255,0,0);
    text("You Lost! \n Game Over:(", 300,200);
    textSize(20);
    text("Press SHIFT to play again",300,500);
    sound_cars.stop();
   
    //restarting the game
    if (keyPressed){
      if (keyCode== SHIFT){
        sound_lost.stop();
        car1x = 750;
        hood1x = 720;
        wheel1a = 825;
        wheel1b = 775;
        car2x = -150;
        hood2x = -50;
        wheel2a = -130;
        wheel2b = -75;
        x= 300;
        y= 370; 
        lives = 3;
        level = 1;
        
        image(background_image,400,280);
        
        scene();
        
        sound_cars.loop();
        }
    }    
 }
}

//displaying instructions of the game
void instructions(){
  
  if (instruct == true){
  background(0);
  fill(#22F0E0);
  textSize(20);
  text("Make the man cross the road without getting hit by a car",100,100);
  text(" ↑ : to move up", 100,125);
  text("↓: to move down", 100,150);
  text(" ←: to move left",100,175);
  text(" → : to move right",100,200);
  text("Press Shift to make the instructions dissappear", 100,225);
  
  textSize(50);
  intro = createFont("STFangsong",32);
  textFont(intro);
  fill(0,0,random(150,255));
  text("DON'T CRASH!",150,500);
  }
  
  //to remove instructions and start the game. 
  if (keyPressed){
    if (keyCode == SHIFT){
      instruct = false;
    }
  }
  
}

 

Midterm in progress: Don’t crash!

Description:

So my assignment is a video game where the player has to cross the road without hitting itself with any of the cars.

Process:

I got this idea while…well, crossing the road. This is just a rough sketch of what I actually wanted to do. The roads are made out of the rectangles. The cars are made using the rectangle with curved edges and ellipses for wheels. Along with a sun in the corner.

For now instead of a sprite sheet, I have used an ellipse for the players to detect the motion. Once the sprite sheet in used it, I expect the figure to have reactions for instances like getting hit by the car. I also plan in adding this image to make the game more realistic:

The speed of the car is randomly chosen between 1 and 5, every time the car leaves the screen so that the player does not get used to the speed. Every time the player is successful in crossing the road, the level increases, and the speed of the car also increases to make the game more difficult. As of now, I have only made the first level.

Also every time the player hits the car, the game restarts. I plan on adding upto 3 lives to this game to make it more intense and interesting. To give it a real life effect I will also add the following picture in the background later since at the moment it is creating an issue with the programme.

Here’s a demo of the game :

Code:

Continue reading “Midterm in progress: Don’t crash!”