Sadie Johnson Final Project

sketch


var gameScreen;
var one, two, three, four, five, six, seven, eight, nine;
//var px = random(800);
var py = random(500);
var Y_AXIS = 1;


function setup() {
	createCanvas(800, 500);
	one = false;
	two = false;
	three = false;
	four = false;
	five = false;
	six = false;
	seven = false;
	eight = false;
	nine = false;
    noStroke();
    frameRate(3);
  // Create objects

  
 
}

function preLoad(){
	 // set gameStarted equal to false
	gameScreen = 0;
	sound1 = loadSound('Himitsu track.wav');
	sound2 = loadSound('coldFunk.wav');
	sound3 = loadSound('iceBeat.wav');
	sound4 = loadSound('game boy startup.wav');
	sound5 = loadSound('japanese-news.wav');
	sound6 = loadSound('child-laughing.wav');
	sound7 = loadSound('calm rain.wav');
	sound8 = loadSound('dialtone.wav');
	sound9 = loadSound('tamagotchi.wav');

}

function draw() {


	//~~~~~~DRAWING OPENING SCREEN~~~~~~
	if (gameScreen == 0){
		initScreen();
	}
	else{
	  if ((key == '2') & (one == false) && (three == false)) {
    key2animation();
    sound2.play();
    two = true;
  }
    if ((key == '3') & (one == false) && (two == false)) {
    key3animation();
    sound3.play();
    three = true;
  }
	if ((key == '4') & (five == false) && (six == false)) {
    key4animation();
    sound4.play();
    four = true;
  }
  if ((key == '5') & (four == false) && (six == false)) {
    key5animation();
    sound5.play();
    five = true;
  }
 if ((key == '6') &  (five == false) && (four == false)) {
    key6animation();
    sound6.play();
    six = true;
  }
if ((key == '7') & (eight == false) && (nine == false)){
	key7animation();
	sound7.play(0);
	seven = true;
}
if ((key == '8') & (nine == false) && (seven == false)){
	key8animation();
	sound8.play();
	eight = true;
}

if ((key == '9') & (seven == false) && (eight == false)){
	key9animation();
	sound9.play();
	nine = true;
}
}
}

function keyTyped() {
  if ((key == '1') & (two == false) && (three == false)) {
    key1animation();
    sound1.play();
    one = true;
  }
 
}
 
function mousePressed(){
  if(gameScreen == 0) {
    gameScreen =1;
    background('#C2D5FF');
  }
}


  function initScreen() {
  	//	background('#F8E9D6')//off-white
  		background('#FCACDF'); //pink, i think
  		fill('#2B4568'); //dark blue
	textSize(100);
	text("ミュージカルキーボード", 5, height/4);
		fill('#26DFEE');//blue
	text("ミュージカルキーボード", 5-3, (height/4)-3);
		textSize(50);
		fill('#26DFEE');//blue
	text("DIGITAL KEYBOARD",width/8+40-3, height/4+23);
 		fill('#2B4568'); //dark blue
	text("DIGITAL KEYBOARD",width/8+40, height/4+20);
  		// get distance between mouse and circle
  var distance = dist(mouseX, mouseY, width/2-40, height/2-10);
  	 if(distance < 50) {
    isOverCircle = true;

  } 
  else {
    isOverCircle = false;
  }
  
  // draw a circle
  ellipseMode(CENTER);

  if(isOverCircle == true)
  {

    fill(100);
    cursor(HAND);
  } else {
    fill(200); 
    cursor(ARROW); 
  }
    fill('#EDECE7');//white
  ellipse(width/2-40, height/2-10, 170, 160);

  stroke('#C45A02');//dark yellow
  strokeWeight(4);
  fill('#FDA102');//medium yellow
  ellipse(width/2-20, height/2, 80, 80);


    
}




function key1animation(){

	//draw blue circles
	noStroke();
   	fill('#1803FF');
 for (i=0; i<15; i++){
  	ellipse(random(width), random(height), 10,10);
 }

 //draw red squares
 for(s=0; s<15; s++){
 	push();
 	fill('#FF0374');
 	rotate(random(1.5));
 	rect(random(800), random(500), 10,10);
 	pop();
 }

 //draw yellow triangles
 for(s=0; s<15; s++){
 	push();
 	fill('#FFFF00');
 	rotate(random(-1));
 	var x=random(800);
 	var y=random(500);
 	triangle(x-10, y, x, y-15, x+10, y);
 	pop();
 }

}

function key2animation(){
	fill('#D0D9D8');
	triangle(0,-50,0,height,width-50,height);
	stroke(51);

	var unit = width/16;
		for (j=1; j<18; j++){
		line(unit*j, 0, unit*j, height);
		}
		for (s=1; s<18; s++){
		line(0, unit*s, width, unit*s);
	}

		
}

function key3animation(){
    for (j=1; j<3; j++){
    fill('#F8CEDA');//pink
    ellipse(random(width),random(height),40,40);
    fill('#C7FFFE'); //bright blue
    ellipse(random(width),random(height),40,40);
    fill('#FFF421');
    ellipse(random(width),random(height),40,40);
}
}

function key4animation(){

	angleMode(DEGREES);
	var rectLength = width/2;
	var rectHeight = height/10;
	var shade = 5;

	fill('#1803FF');//blue
	rect(width/2,50,rectLength,rectHeight);
	 fill('#FCACDF');//pink
	 rect(width/2-shade,50-shade,rectLength,rectHeight);
	 if(frameCount%2==0){
	 	fill('white');
	 	textSize(50);
	 	text("S-U-M-M-E-R",width/2+shade,87);
	 }

 push();
  	rotate(30);
 	fill('#1803FF');//blue
	rect(50,50,rectLength,rectHeight);
	rect(100,70+rectHeight,rectLength,rectHeight);

	 fill('#FCACDF');//pink
	 rect(50-shade,50-shade,rectLength,rectHeight);
	rect(100-shade,70+rectHeight-shade,rectLength,rectHeight);
	pop();


}
function key5animation(){
	var moonSize=100;
    noStroke();

    //DRAWS THE ECLIPSE EFFECT BEHIND THE MOON
   for (var i=0; i<10; i++){ //the glow is made of 20 overlapping circles
        fill(255,211,67,i);// semi-transparent yellow glow
        ellipse(width/5, height/5-7, moonSize+(10*i), moonSize+(10*i));
    }

    //DRAWS OPAQUE HIGHLIGHT BEHIND MOON
    fill('#EFEEE9'); //opaque, light yellow
    ellipse(width/5, height/5-3, moonSize+2, moonSize+2);

    //DRAWS THE MOON
    fill('#F8CEDA'); //light orange
    ellipse(width/5, height/5, moonSize, moonSize);

  
}
function key6animation(){
	var x = 0;
	var y = 0;
	var unit =20;
	if (frameCount%2==0){
	fill('#1803FF');//blue
	rect(x,y,width*.75,40);
	fill('#FF0374');//red
	rect(x+unit,y+40+unit,width*.75,40);
	fill('#FFFF00');//yellow
	rect(x+unit*2,y+80+unit*2,width*.75,40);
}
	 else{
		fill('#FFFF00');//yellow
	
	rect(x,y,width*.75,40);
	fill('#1803FF');//blue
	
	rect(x+unit,y+40+unit,width*.75,40);
	fill('#FF0374');//red
	rect(x+unit*2,y+80+unit*2,width*.75,40);
	}

}

function key7animation(){
	fill('#FE0097')//pink
	textSize(100);
	push();
	rotate(frameCount / -100.0);
	text("アテネの夕焼け", 0, height/2);
	pop();
}

function key8animation(){
	 if(frameCount%2==0){
	 var c1 = color('#F5D0D7');
  	var c2 = color('#7CF0CD');
  }
  	 if(frameCount%2==1){
  	 	var c2 = color('#F5D0D7');
  	var c1 = color('#7CF0CD');
  }
	setGradient((width/2)-100, (height/2)-100, 200, 200, c1, c2, Y_AXIS);

}
function key9animation(){
	var diskSize=150;
	var roundedness =10; //how rounded corners of rectangles are
	fill('#3D3C41');//grey
rect(width/2, height/2, diskSize+20, diskSize,roundedness);
fill('#C2C1BD');//light grey
rect(width/2+20, height/2, diskSize-30, 40,roundedness);
fill('#424146');//medium grey
rect(width/2+20, height/2, 25, 40);
rect(width/2+100, height/2+5, 15, 30);
fill('#FFFFFF');//white
rect(width/2+20, height/2+70, diskSize-10, diskSize/2,roundedness);
	}



function setGradient(x, y, w, h, c1, c2, axis) {

  noFill();

  if (axis == Y_AXIS) {  // Top to bottom gradient
    for (var i = y; i <= y+h; i++) {
      var inter = map(i, y, y+h, 0, 1);
      var c = lerpColor(c1, c2, inter);
      stroke(c);
      line(x, i, x+w, i);
    }
  }  
}



Charlie Mo Final

link to project: http://charliemo.neocities.org/raining%20night/index.html

Sorry about the late hand-in, this is unacceptable but my goal is to make the best project I possibly can.

I created a world in a bleak distant future where overpopulation and reliance of technology becomes common place. The visuals are inspired by Japanese animator Hayao Miyazaki, who produced the likes of Spirited Away and Howl’s Moving Castle, and I attempted to replicate the style by combining traditional Asian architecture with apartment building commonly found in crowded urban living environments.

*Spacebar to fly!*

night

sketch

var bird;
var pipes = [];
var build1;
var build2;
var build3;
var build4;
var cloud1;
var cloud2;
var pole;
var drops =[];
//var sound;


function preload(){
  
  build1 = loadImage("assets/building1.png");
  build2 = loadImage("assets/building2.png");
  build3 = loadImage("assets/building3.png");
  build4 = loadImage("assets/building4.png");
  cloud1 = loadImage("assets/cloud.png");
  cloud2 = loadImage("assets/cloud3.png");
  cloud3 = loadImage("assets/cloud4.png");
  pole   = loadImage("assets/pole2.png");
  skyline= loadImage("assets/skyline3.png");
  //rain = loadSound("assets/rain.mp3");
}

function setup() {
  createCanvas(600,800);
    //spawns bird and in setup() so that 
    //the bird can be updated
  bird = new Bird();
    //spawns rainfall
  for (var i = 0; i < 500; i++) {
    drops[i] = new Drop();
  }
  
}

function draw() {
  
  fill(255);
  background(200)
    //background image
  image(skyline,-500,0)
  
  for (var i = 0; i < drops.length; i++) {
    drops[i].fall();
    drops[i].show();
  }

  for (var b = pipes.length-1; b >= 0; b--){
    pipes[b].show();
    pipes[b].update();

  }
    //determines the rate at which
    //sprites are added to the array
  if (frameCount%300 == 0){
    pipes.push(new Build1())
  }
  if (frameCount%200 == 0){
    pipes.push(new Build2())
  }
  if (frameCount%100 == 0){
    pipes.push(new Build3())
  }
  if (frameCount%350 == 0){
    pipes.push(new Build4())
  }
  if (frameCount%500 == 0){
    pipes.push(new Cloud1())
  }
  if (frameCount%400 == 0){
    pipes.push(new Cloud2())
  }
  if (frameCount%320 == 0){
    pipes.push(new Pole())
  }
  if (frameCount%300 == 0){
    pipes.push(new Pole2())
  }
  if (frameCount%310 == 0){
    pipes.push(new Pole3())
  }
  
  bird.update();
  bird.show();
}

    //press to make character fly
function keyPressed(){

  if (key == ' '){
    bird.up();
    //sound.play();
    //calls from Bird function
  }

}

    //determines speed and positioning of the sprites
function Cloud2(){
this.x = width*2;
this.velocity = 0;
this.speed = 3;

  this.show = function(){
    image(cloud2,this.x,50)
  }
 
  this.update = function(){
    
    this.x -= this.speed;
    
  this.offscreen = function() {
    if (this.x < -this.w) {
      return true;
    } else {
      return false;
    }
  }
  }
}
function Build1(){
 this.x = width*2;
 this.velocity = 0;
 this.speed = 2.5;

  this.show = function(){
    
      image(build1,this.x,250)

  }
  
  
  this.update = function(){
    
    this.x -= this.speed;
    
    
    this.offscreen = function() {
    if (this.x < -this.w) {
      return true;
    } else {
      return false;
    }
  }
    
  }
}
function Build2(){
 this.x = width*2;
 this.w = random(70,120);
 this.velocity = 0;
 this.speed = 2.5;

  this.show = function(){
    
      image(build2,this.x,400)

  }

  
  this.update = function(){
    
    this.x -= this.speed;
    
    
    this.offscreen = function() {
    if (this.x < -this.w) {
      return true;
    } else {
      return false;
    }
  }
    
  }
}
function Build3(){
 this.x = width*2;
 this.w = random(70,120);
 this.velocity = 0;
 this.speed = 2.5;

  this.show = function(){
    
      image(build3,this.x,400)

  }

  this.update = function(){
    
    this.x -= this.speed;
    
    
    this.offscreen = function() {
    if (this.x < -this.w) {
      return true;
    } else {
      return false;
    }
  }
    
  }
}
function Build4(){
 this.x = width*2;
 this.w = random(70,120);
 this.velocity = 0;
 this.speed = 2.5;

  this.show = function(){
    
      image(build4,this.x,100)

  }

  this.update = function(){
    
    this.x -= this.speed;
    
    
    this.offscreen = function() {
    if (this.x < -this.w) {
      return true;
    } else {
      return false;
    }
  }
    
  }
}
function Cloud1(){
this.x = width/6;
this.w = random(70,120);
this.velocity = 0;
this.speed = 1;

  this.show = function(){
    
      image(cloud1,this.x-500,600)

  }

  this.update = function(){
    
    this.x -= this.speed;
    
    
    this.offscreen = function() {
    if (this.x < -this.w) {
      return true;
    } else {
      return false;
    }
  }
    
  }
}
function Pole(){
this.x = width*2;
this.w = random(70,120);
this.velocity = 0;
this.speed = 2.5;

  this.show = function(){
    
      image(pole,this.x,230)

  }
  
  this.update = function(){
    
    this.x -= this.speed;
    
    
    this.offscreen = function() {
    if (this.x < -this.w) {
      return true;
    } else {
      return false;
    }
  }
    
  }
}
function Pole2(){
this.x = width*2;
this.w = random(70,120);
this.velocity = 0;
this.speed = 2.5;

  this.show = function(){
    
      image(pole,this.x,300)

  }

  this.update = function(){
    
    this.x -= this.speed;
    
    
    this.offscreen = function() {
    if (this.x < -this.w) {
      return true;
    } else {
      return false;
    }
  }
    
  }
}
function Pole3(){
this.x = width*2;
this.w = random(70,120);
this.velocity = 0;
this.speed = 2.5;

  this.show = function(){
    
      image(pole,this.x,350)

  }
  
  this.update = function(){
    
    this.x -= this.speed;
    
    
    this.offscreen = function() {
    if (this.x < -this.w) {
      return true;
    } else {
      return false;
    }
  }
    
  }
}


    //CHARACTER
function Bird() {
  this.y = height / 2;
  this.x = 300;

  this.gravity = 0.2;
  this.lift = -30;
  this.velocity = 0;

  this.show = function() {
    //character creation
    fill(55);
    noStroke();
    rectMode(CENTER);
    rect(this.x,this.y-30,2,80);
    arc(this.x,this.y-40,50,50,-PI,PI);
    fill(0);
    ellipse(this.x, this.y, 32, 32);
    fill(250, 222, 222);
    ellipse(this.x-5,this.y+2,5,5);
    ellipse(this.x+8,this.y+2,5,5);
  }

  this.up = function() {
    //determines the up speed in terms of 
    //the already established this.lift variable
    this.velocity += this.lift;
  }

  this.update = function() {
    //simulate gravity and updates this.y with 
    //new position
    this.velocity += this.gravity;
    this.velocity *= 0.9;
    this.y += this.velocity;
    
    //set boundaries on the canvas
    if (this.y > height) {
      this.y = height;
      this.velocity = 0;
    }

    if (this.y < 0) {
      this.y = 0;
      this.velocity = 0;
    }
  }
}

    //RAIN
function Drop() {
    //random x position
  this.x = random(width);
    //random y position from beyond the canvas
  this.y = random(-500, -50);
  this.len = random(10,20);
  this.yspeed = random(4,10)

  this.fall = function() {
    
      //speed at which the drop will fall
    this.y = this.y + this.yspeed;
      //simulate gravity
    var gravity = 0.4
    this.yspeed = this.yspeed + gravity;

    if (this.y > height) {
        //resets raindrops 
      this.y = random(-200, -100);
      this.yspeed = random(4,10)
    }
  }

  this.show = function() {
    strokeWeight(1);
    stroke(235);
    line(this.x, this.y, this.x, this.y+this.len);
  }
}

AndrewWang-Final-Project-PaintTool

*Sorry this was submitted a day late (I still have a grace day if that counts), I was really busy and thought I had submitted it earlier. I actually finished it last week, but wanted to hold off submitting it in case I decided to change anything.

date

I deployed the project using Zeit onto https://ns-dmpwapvltg.now.sh/

For my project I tried to replicate a paint program that allows the users to draw things using tools. I started with the generic tools such as pencil, rectangle, ellipse, eraser, text, and line, creating an object to add to an array that is drawn over each time draw() is ran.

I then created a way to both undo and redo objects using z and y by popping the last element in the drawn array onto a stack, and moving pieces from the stack back to the array when redoing. The stack is cleared if the user draws again. I also made it possible to save the image by pressing s, redrawing over the text tool bar to allow for a cleaner saved image.

I used prompt in order to get the values that the users would need to input when using these tools, otherwise piping to a default value to avoid nils. If I had more time I would have created form fields that the user would be able to interact with more freely and less intrusively.

files:

104-project

zhuoyinl-final project

%e5%be%ae%e4%bf%a1%e6%88%aa%e5%9b%be_20161210011151

For this project, I made a abstract keyboard that generate animations for each note, using some conmic icon to represent traditional keyboard.

sketch

var osc;
var env;
var dir = 1;
var speed = 10;
var diam = 20;
var col;
var isRed = [] 
var x1 = 50
var x2 = 25;
var y2 =25;
var x3 = 50;
var y3 = 0;
var x4 = 50;
var y4 = 800;
var x5 = 400;
var y5 = 0;
var x6 = 0;
var y6 = 400;
var x7 = 400;
var y7 = 40;
var terrainSpeed1 = 0.0005;
var terrainDetail1 = 0.0001227;


  
function setup() {
  createCanvas(800,800)
  osc = new p5.Oscillator();
  osc.setType('sine');//set sound type

  for (var i = 0; i < 10; i++){
        var rx = random(width);
        var ry = random(0,height/4);     
    }//set up background flow   
  frameRate(100);
   
}

function draw() {
  background(254,175,188)

  

  push();
  fill(154,231,217); 
  beginShape(); 
  noStroke();
  for (var x = 0; x < width; x++) {
      var t = (x * terrainDetail1) + (millis() * terrainSpeed1);
      var y = map(noise(t), 0,1, height/4, height*3/4);
      vertex(x, y); 
    
  }
  vertex(width, height);
  vertex(0,height);
  endShape();
  pop();//background moving pattern


  drawKeyBoard();
  if (keyCode==49){   
      drawCircle(); 
  }else if (keyCode==50){
    drawball1();
  }else if (keyCode==51){
    drawLine();
  }else if (keyCode==52){
    drawball2();
  }else if (keyCode==53){
    drawSquare();
  }else if (keyCode==54){
    drawball3();
  }else if (keyCode==55){
    drawRing();
  }else if (keyCode==56){
    drawball4();
  }else if (keyCode==57){
    drawSquare2();
  }else if (keyCode==48){
    drawduck();
  }//assign animation for each sound

  push();
  strokeWeight(0);
  stroke(0);
  textSize(20);
  textStyle(BOLD);
  textFont("Helvetica");
  text("Press number key to start", 280, 760);
  pop();//instruction
 
}


//make each animation
function drawCircle(){
  
  noStroke();
  fill(col);
  ellipse(width/2, height*2/5, diam, diam);

  diam += dir * speed;
  if (diam > 200) {
      dir = -dir;
      diam = 200;
  } else if (diam < 0) {
      dir = -dir;
      diam = 0;
  }
     
}

function drawLine(){
  push();
  translate(width/2,height*2/5);
  for(var j = 0;j<10;j++){
    rotate(radians(36));
    stroke(163,228,37);
    strokeWeight(5);
    line(0,0,x1,0);
    x1+=dir*speed*0.08
    if (x1 > 200) {
      dir = -dir;
      x1 = 200;
    } else if (x1 < 0) {
      dir = -dir;
      x1 = 0;
    }

  }
  pop();
}

function drawRing(){
  stroke(154,231,217);
  strokeWeight(10);
  noFill();
  ellipse(width/2, height*2/5, diam, diam);
  diam += dir * speed;
  if (diam > 200) {
      dir = -dir;
      diam = 200;
  } else if (diam < 0) {
      dir = -dir;
      diam = 0;
  }
}

function drawSquare(){
  push();
  translate(width/2,height*2/5);
  noStroke();
  fill(207,214,251);
  quad(-x2,-y2,x2,-y2,x2,y2,-x2,y2);
  
  x2 += dir * speed;
  y2 +=dir*speed;
  if (x2 > 200) {
      dir = -dir;
      x2 = 200;
  } else if (x2 < 0) {
      dir = -dir;
      x2 = 0;
  }

}

function drawSquare2(){
  push();
  translate(width/2,height*2/5);
  stroke(112,208,236);
  strokeWeight(5);0
  noFill();
  quad(-x2,-y2,x2,-y2,x2,y2,-x2,y2);
  
  x2 += dir * speed*0.9;
  y2 +=dir*speed*0.9;
  if (x2 > 200) {
      dir = -dir;
      x2 = 200;
  } else if (x2 < 0) {
      dir = -dir;
      x2 = 0;
  }

}

function drawball1(){
  noStroke();
  fill(255,240,162);
  ellipse(x3, y3, 50, 50);
  x3 += dir * speed*2;
  y3 +=dir*speed*2;
  if (x3 > 800) {
      dir = -dir;
      x3 = 800;
  } else if (x3 < 0) {
      dir = -dir;
      x3 = 0;
  }

}

function drawball2(){
  noStroke();
  fill(166,159,255);
  ellipse(x4, y4, 50, 50);
  x4 += dir * speed*2;
  y4 +=-1*dir*speed*2;
  if (x4 > 800) {
      dir = -dir;
      x4 = 800;
  } else if (x4 < 0) {
      dir = -dir;
      x4 = 0;
  }

}

function drawball3(){
  noStroke();
  fill(166,108,148);
  ellipse(x5, y5, 50, 50);
  x5 += dir * speed*0.5;
  y5 += dir*speed*2;
  if (y5 > 800) {
      dir = -dir;
      y5 = 800;
  } else if (y5 < 0) {
      dir = -dir;
      y5 = 0;
  }
}

function drawball4(){
  noStroke();
  fill(255,115,118);
  ellipse(x6, y6, 50, 50);
  x6 += dir * speed*2;
  y6 += dir*speed*0.5;
  if (x6 > 800) {
      dir = -dir;
      x6 = 800;
  } else if (x6 < 0) {
      dir = -dir;
      x6 = 0;
  }
}

function drawduck(){
  noStroke();
  fill(255,115,118);
  duck(x7, y7, 50, 50);
  x7 += dir * speed*2;
  y7 += dir*speed;
  if (x7 > 800 ) {
      dir = -dir;
      x7 = 800;
  } else if (x7 < 0) {
      dir = -dir;
      x7 = 0;
  }
}



//monster keyboard
function drawKeyBoard(){
  var index = map(keyCode,48,57,0,9);
  for (var i = 0;i<9;i++){
      monster(i*80+40,height*5/6,-25);
      if (keyIsPressed===true){
        monster((index-1)*80+40,height*5/6,-50*index);
    }else{
      monster(i*80+40,height*5/6,-25);
    }
  }
}

// animation pattern-duck
function duck(dx, dy) {//draw duck
    push();
    translate(dx, dy);
    stroke(255, 183, 0);
    strokeWeight(5);
    line(-15, 60, -15, 85);//foot1
    line(-5, 60, -5, 85);//foot2
    stroke(154, 231, 217);
    strokeWeight(40);
    line(0, 0, 0, 30);//neck
    strokeWeight(40);
    line(-30, 40, 0, 40);//body
    strokeWeight(10);
    line(-55, 40, -30, 40);//tail
    stroke(255, 183, 0);
    strokeWeight(7);
    line(10, 7, 25, 7);//mouse
    line(10, 14, 25, 14);//mouse
    fill(255);
    noStroke();
    ellipse(0, 0, 10, 10);//eye
    fill(0);
    noStroke();
    ellipse(1, 0, 5, 5);



    pop();
}


//keyboard pattern-monster
function monster(mx, my,earl) {//draw monster
    push();
    translate(mx, my);
    stroke(137,78,115);
    strokeWeight(5);
    line(25, earl, 25, 0);//ear1
    line(45, earl, 45, 0);//ear2
    line(30, 30, 85, 40);//tail
    stroke(244,179,220);
    strokeWeight(30);
    line(10, 0, 50, 0);//monster head
    strokeWeight(5);
    line(35, 40, 35, 60);//foot1
    line(45, 40, 45, 60);//foot2
    line(55, 40, 55, 60);//foot3
    line(65, 40, 65, 60);//foot4
    strokeWeight(50);
    line(50, 10, 50, 30);//monster body
    fill(255);
    noStroke();
    ellipse(22, 0, 15, 15);//left eye
    ellipse(42, 0, 15, 15);//right eye
    fill(0);
    noStroke();
    ellipse(20, 0, 5, 5);//eyeball1
    ellipse(40, 0, 5, 5);//eyeball2
    pop();
}

//assign sound to each key
function keyPressed(){

  if (keyCode == 49){
     osc.freq(174);
     osc.amp(0);
     osc.start();
     osc.stop(0.25);
     osc.amp(1, 0.05);
     col = ('yellow');

  }else if (keyCode == 50){
     osc.freq(196);
     osc.amp(0);
     osc.start();
     osc.stop(0.25);
     osc.amp(1, 0.05);
     col = ('blue');
  }else if (keyCode == 51){
     osc.freq(220);
     osc.amp(0);
     osc.start();
     osc.stop(0.25);
     osc.amp(1, 0.05);
     col = ('');
  }else if (keyCode == 52){
     osc.freq(233);
     osc.amp(0);
     osc.start();
     osc.stop(0.25);
     osc.amp(1, 0.05);
     col = ('blue');
  }else if (keyCode == 53){
     osc.freq(261);
     osc.amp(0);
     osc.start();
     osc.stop(0.25);
     osc.amp(1, 0.05);
     col = ('blue');
  }else if (keyCode == 54){
     osc.freq(293);
     osc.amp(0);
     osc.start();
     osc.stop(0.25);
     osc.amp(0.5, 0.05);
     col = ('blue');
  }else if (keyCode == 55){
     osc.freq(329);
     osc.amp(0);
     osc.start();
     osc.stop(0.25);
     osc.amp(0.5, 0.05);
     col = ('blue');
  }else if (keyCode == 56){
     osc.freq(349);
     osc.amp(0);
     osc.start();
     osc.stop(0.25);
     osc.amp(0.5, 0.05);
     col = ('blue');
  }else if (keyCode == 57){
     osc.freq(392);
     osc.amp(0);
     osc.start();
     osc.stop(0.25);
     osc.amp(0.5, 0.05);
     col = ('blue');
  }else if (keyCode == 48){
     osc.freq(440);
     osc.amp(0);
     osc.start();
     osc.stop(0.25);
     osc.amp(0.5, 0.05);
     col = ('blue');
  }

     else {osc.amp(0, 0.5);
     } 
  
}

GarrettRauck-Final Project

sketch

//Garrett Rauck
//Section C
//grauck@andrew.cmu.edu
//Assignment-07a-Bar Chart

// prevent scrolling of page
// from "Single Touch with P5js" on coursescript.com
// http://coursescript.com/notes/interactivecomputing/mobile/touch/
document.ontouchmove = function(event){
  event.preventDefault();
}

/////////////////////////////////
// INIT VARIABLES
/////////////////////////////////
//MODEL
var mode;
var selection;
//temp node
var tempNodeX, tempNodeY;
var tempNodeContent = "";
//data
var nodes = [];
var links = [];
//VIEW
//canvas vars
var canvasWidth, canvasHeight;
//colors
var colorBG, colorNode, colorSelection, colorLink;
//font
var font, fontSize;


/////////////////////////////////
// NODE CLASS
/////////////////////////////////
//CREATE NEW NODE, called when user clicks the canvas
function newNode(xIn, yIn) {
	//update app state
	mode = "GETTING NODE CONTENT";
	//store temporary node location
	tempNodeX = xIn;
	tempNodeY = yIn;
	tempNodeContent = "";
}

function saveNewNode() {
	println("SAVE NEW NODE!");
	//get bounding box for node
	var bounds = fontRegular.textBounds(
		tempNodeContent, tempNodeX, tempNodeY, fontSize);
	var offset = 5;
	//create new node instance using temp data
	var newNode = {x: tempNodeX,
	               y: tempNodeY,
	               content: tempNodeContent,
	               left: bounds.x - offset,
	               right: bounds.x + bounds.w + offset,
	               top: bounds.y - offset,
	               bottom: bounds.y + bounds.h + offset,
	               move: moveNode,
	               draw: drawNode};
	//store the new node
	nodes.push(newNode);
	//update app state
	mode = "MAP";
}

function abortNewNode() {
	println("ABORT NEW NODE!");
	tempNodeContent = "";
	mode = "MAP";
}

//MOVE SPECIFIED NODE
function moveNode(dx,dy) {
	this.x += dx;
	this.y += dy;
	this.left += dx;
	this.top += dy;
	this.right += dx;
	this.bottom += dy;
}

//DRAW SPECIFIED NODE
function drawNode() {
	if (this == selection) {
		//draw node border
		setDrawingSettings("NODE BORDER SELECTION");
		rect(this.left,this.top,this.right,this.bottom);
		//draw node text
		setDrawingSettings("NODE TEXT SELECTION");
		text(this.content,this.x,this.y);
	}
	else {
		//draw node border
		setDrawingSettings("NODE BORDER");
		rect(this.left,this.top,this.right,this.bottom);
		//draw node text
		setDrawingSettings("NODE TEXT");
		text(this.content,this.x,this.y);
	}
}


/////////////////////////////////
// LINK CLASS
/////////////////////////////////
//CREATE LINK BETWEEN TWO NODES
function newLink(fromIn, toIn) {
	var newLink = {from: fromIn,
	               to: toIn,
	               draw: drawLink};
	links.push(newLink);
}

function drawLink() {
	setDrawingSettings("LINK");
	line(this.from.x, this.from.y, this.to.x, this.to.y);
}

/////////////////////////////////
// VIEW
/////////////////////////////////
function setDrawingSettings(setting) {
	if (setting == "NODE TEXT") {
		noStroke();
		fill(colorNode);
		textAlign(CENTER);
	}
	else if (setting == "NODE TEXT SELECTION") {
		noStroke();
		fill(colorSelection);
		textAlign(CENTER);
	}
	else if (setting == "NODE BORDER") {
		stroke(colorNode);
		fill(colorBG);
	}
	else if (setting == "NODE BORDER SELECTION") {
		stroke(colorSelection);
		fill(colorBG);
	}
	else if (setting == "LINK") {
		stroke(colorLink);
		noFill();
	}
}

//DRAW TEMPORARY NODE WHILE EDITING
function drawTempNode() {
	//drawing settings
	setDrawingSettings("NODE TEXT SELECTION");
	//draw text
	text(tempNodeContent, tempNodeX, tempNodeY);
}

//DRAW ALL NODES IN MAP
function drawAllNodes() {
	for (i=0; i<nodes.length; i++) {
		node = nodes[i];
		node.draw();
	}
}

function drawAllLinks() {
	for (i=0; i<links.length; i++) {
		link = links[i];
		link.draw();
	}
}

/////////////////////////////////
// CONTROLLER
/////////////////////////////////
//CHECK CLICK IS ON EXISTING NODE, RETURN THAT NODE
function clickIsNode() {
	//for each existing node...
	for (i=0; i<nodes.length; i++) {
		var node = nodes[i];
		//check if click was within the node bounding box
		if ((node.left <= mouseX) & (mouseX <= node.right) &&
			(node.top <= mouseY) && (mouseY <= node.bottom)) {
			//return the node object
			return node;
		}
	}
	return false;
}

function clickIsCanvas() {
	if ((mouseX > 0) & (mouseX < width) &&
		(mouseY > 0) && (mouseY < height)) {
		return true;
    }
    else return false;
}

function mousePressedMap() {
	//if node is already selected...
	if (selection) {
		//if user clicks the blank canvas, deselect
		if (! clickIsNode()) {
			println("DESELECT!");
			selection = null;
		}
		//else if user clicks another node, create link
	    else if (clickIsNode()) {
	    	if (keyCode == 16) { //shift-click another node, create link
	    		println("NEW LINK!");
	    		var secondSelection = clickIsNode();
	    		newLink(selection,secondSelection);
	    		//clear selection
	    		selection = null;
	    	}
	    	else selection = clickIsNode();	
	    }
	}
	//if nothing selected...
	else {
		//if user clicks an existing node, select that node
		if (clickIsNode()) {
			println("NODE SELECTED!");
			selection = clickIsNode(); // <-- figure out a more efficient method...
		}
		else if (! clickIsNode()) {
			//initialize new node
			println("NEW NODE!");
		    newNode(mouseX,mouseY);
		}
	}
}

function mousePressed() {
	if (mode == "MAP") {
		mousePressedMap();
	}
}

function mouseDraggedMap() {
	//if user is dragging a selected node
	if (selection) {
		//get drag data
		var dx = mouseX - pmouseX;
		var dy = mouseY - pmouseY;
		//move selected node
		selection.move(dx,dy);
	}
}

function mouseDragged() {
	if (mode == "MAP") {
		mouseDraggedMap();
	}
}

function keyPressedMap() {
	if (keyCode == 27) selection = null;
}

function keyPressedGettingNodeContent() {
	//"ENTER", save new node
	if (keyCode == 13) saveNewNode();
	//"ESCAPE", abort new node
	else if (keyCode === 27) abortNewNode();
	//"BACKSPACE", delete previous character
	else if (keyCode === 8) {
		tempNodeContent = 
			tempNodeContent.substring(0, tempNodeContent.length-1);
	}
	//Other character...
	else tempNodeContent += key;
}

function keyPressed() {
	println("key = " + key);
	println("keyCode = " + keyCode);

	if (mode == "MAP") {
		keyPressedMap();
	}
	else if (mode == "GETTING NODE CONTENT") {
		keyPressedGettingNodeContent();
	}
}

/////////////////////////////////
// RUN!
/////////////////////////////////
function preload() {
	fontRegular = loadFont('cour.ttf');
	fontBold = loadFont('courbd.ttf');
	fontItalic = loadFont('couri.ttf');
	fontBoldItalic = loadFont('courbi.ttf');
}

function setup() {
	////////// INIT VARS //////////
	// MODEL
	mode = "MAP"; // initial app state
	selection = null;
	//canvas
	canvasWidth = canvasHeight = 400;
	//font
	fontSize = 12;
	//color
	colorBG = color(255,255,255);
	colorNode = color(0,0,0);
	colorSelection = color(255,127,0);
	colorLink = colorNode;

	//DRAWING SETTINGS
	rectMode(CORNERS);
	textFont(fontBold);

	// CANVAS SETUP
    createCanvas(canvasWidth, canvasHeight);
}

function draw() {
	background(colorBG); //update background

	//draw nodes
	drawAllLinks();
	drawAllNodes();

	if (mode == "GETTING NODE CONTENT") {
		drawTempNode();
	}
}

My final project was an attempt to make a digital mind-mapping interface. A mind-map is a tool for thinking through complex problems in which the user draws nodes which represent ideas and then draws connections between those nodes to develop complex relationships. A digital mind-mapping interface would transcend the traditional limits of the paper medium.

Unfortunately, the sketch uploaded to WordPress can’t run because I have been unable to find a way to load a font, which I need in order to use the textBounds() function for click detection.

When it’s working locally on my computer, the user can click or touch the screen to begin creating a node. The user can type in text for the node, then press enter to finalize the node. The user can continue to do this to create multiple nodes. If the user clicks an existing node, that node becomes selected. The user can click and drag a node to move it on the canvas. If the user has one node selected and shift-clicks another node, a link is created between those nodes. As the user moves nodes that are linked, the link is preserved.

To be honest, I haven’t been able to put a lot of time into this project, so this is where it’s at. I also developed a touch-screen drawing interface. I was hoping to integrate the two sketches into a mind-mapping interface involving touch-face drawing. Here is that sketch:

sketch

//Garrett Rauck
//Section C
//grauck@andrew.cmu.edu
//Final Project - Sketch - 2016/11/26

// prevent scrolling of page
// from "Single Touch with P5js" on coursescript.com
// http://coursescript.com/notes/interactivecomputing/mobile/touch/
document.ontouchmove = function(event){
  event.preventDefault();
}

///////////////////////////////////////////////////////////////////////////////
// GLOBAL VARIABLES
///////////////////////////////////////////////////////////////////////////////
//MODEL VARIABLES
var mode; //the current mode. possible values: "MAP", "NODE EDIT"
var currentSelection; //the currently selected object. null if nothing selected
var OX, OY; //x and y location of the map origin, relative to 0,0
var nodes = []; //array to store all node instances
var links = []; //array to store all link instances
var currentScribble;
//EVENT VARIABLES
var timeOfLastClick, //time in milliseconds of the previous mouse click
    doubleClickThreshold; //time in milliseconds allowed for double-click

///////////////////////////////////////////////////////////////////////////////
// TEXT NODE CLASS
///////////////////////////////////////////////////////////////////////////////
function textNodeDraw() {
	return;
}

function textNodeUpdateVPLocation() {
	println("textNodeUpdateVPLocation()")
}
///////////////////////////////////////////////////////////////////////////////
// SCRIBBLE NODE CLASS
///////////////////////////////////////////////////////////////////////////////
function scribbleNodeAddPoint(x,y) {
	println(this.ptsX);
	this.ptsX.push(x);
	this.ptsY.push(y);
}

function scribbleNodeDraw() {
	stroke(255);
	beginShape();
	for (var i=0; i<this.ptsX.length; i++) {
		var x = this.ptsX[i];
		var y = this.ptsY[i];
		vertex(x,y);
	}
	endShape();
}

function scribbleNodeUpdateVPLocation(dx,dy) {
	//update drawing vertices relative to map origin
	for (var i=0; i<this.ptsX.length; i++) {
		this.ptsX[i] += dx;
		this.ptsY[i] += dy;
	}
}

///////////////////////////////////////////////////////////////////////////////
// MODEL HELPER FNS
///////////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
//NODES
function newNode(type,x,y) {
	println("New " + type + " node!");
	var newNode;
	if (type == "TEXT") newNode = newTextNode(x,y);
	else if (type == "SCRIBBLE") newNode = newScribbleNode(x,y);
	//store new node in array of existing nodes
	nodes.push(newNode);
	//return new node
	return newNode;
}
function newTextNode(xIn,yIn) {
	println("Creating new TEXT node...");
	//create new text node instance
	var textNode = {x: xIn, //x pos of node relative to map origin
	                y: yIn, //y pos of node relative to map origin
	                type: "TEXT", //node type
	                updateVPLocation: textNodeUpdateVPLocation, //fn for update
	                draw: textNodeDraw}; //fn to draw node
	return textNode;
}
function newScribbleNode(xIn,yIn) {
	println("Creating new SCRIBBLE node...");
	//create new scribble node instance
	var scribbleNode = {x: xIn,
	                    y: yIn,
	                    type: "SCRIBBLE",
	                    ptsX: [xIn],
	                    ptsY: [yIn],
	                    addPoint: scribbleNodeAddPoint,
	                    updateVPLocation: scribbleNodeUpdateVPLocation,
	                    draw: scribbleNodeDraw};
	return scribbleNode;
}

//-----------------------------------------------------------------------------
//VIEW
function pan(dx,dy) {
	//update node locations
	for (var i=0; i<nodes.length; i++) {
		var node = nodes[i];
		node.updateVPLocation(dx,dy);
	}
}

///////////////////////////////////////////////////////////////////////////////
// DRAW HELPER FNS
///////////////////////////////////////////////////////////////////////////////
function drawAllNodes() {
	noFill();
	strokeWeight(3);
	for (var i=0; i<nodes.length; i++) {
		var node = nodes[i];
		node.draw();
	}
}
///////////////////////////////////////////////////////////////////////////////
// EVENTS
///////////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
//TOUCH STARTED
//called when user touches the screen within the javascript canvas
function touchStarted() {
	println("Touch!");
	println(touches);
	if      (mode == "MAP")       touchStartedMap();
	else if (mode == "NODE EDIT") touchStartedNodeEdit();
	//Important! Returning false prevents mousePressed() from also firing,
	//which would confuse the double-click functionality. 
	return false;
}
//called when user touches the screen while in the MAP mode
function touchStartedMap() {
	var timeOfCurrentTouch = millis()
	var timeSinceLastTouch = timeOfCurrentTouch- timeOfLastClick;
	//if user touches blank space on canvas
		//if single-tap, DESELECT
		if ((timeSinceLastTouch > doubleClickThreshold) &
		    (touches.length < 2)) {
			//deselect
			currentSelection = null;
		}
		//else if double-tap, NEW TEXT NODE
		else if ((timeSinceLastTouch <= doubleClickThreshold) &
		         (touches.length < 2)) {
			//create new text node
			newNode("TEXT",touchX,touchY);
		}
	//else if user touches an existing node

	//store time of current click
	timeOfLastClick = timeOfCurrentTouch;
}
//-----------------------------------------------------------------------------
//TOUCH MOVED
//called when user touches and drags their finger
function touchMoved() {
	if      (mode == "MAP")       touchMovedMap();
	// else if (mode == "NODE EDIT") touchMovedNodeEdit();
}
//called when user touches and drags their finger while in MAP mode
function touchMovedMap() {
	//if single finger drag, SCRIBBLE
	if (touches.length == 1) {
		//if not already scribbling, NEW SCRIBBLE NODE 
		if (currentScribble == null) {
			currentScribble = newNode("SCRIBBLE",touchX,touchY);
		}
		//else if already scribbling, ADD POINT to current scribble
	    else currentScribble.addPoint(touchX,touchY);
	}
	//else if two finger drag, PAN
	else if (touches.length == 2) {
		println("Pan!")
		pan(touchX-ptouchX, touchY-ptouchY);
	}
}
//-----------------------------------------------------------------------------
//TOUCH ENDED
//called when user releases his/her finger from the screen
function touchEnded() {
	if      (mode == "MAP")       touchEndedMap();
	// else if (mode == "NODE EDIT") touchEndedNodeEdit();
}
//called when user realeases his/her finger from the screen while in map mode
function touchEndedMap() {
	//if user is drawing scribble, stop scribbling
	if (currentScribble != null) {
		currentScribble = null;
	}
}

///////////////////////////////////////////////////////////////////////////////
// RUN!
///////////////////////////////////////////////////////////////////////////////
//function used to initialize the variables
function initVars() {
	// INIT VARS
	timeOfLastClick = 0;
	doubleClickThreshold = 200;
	currentScribble = null;
	//SET MODEL STATE
	mode = "MAP";
	//Canvas
	canvasWidth = canvasHeight = 400;
}
//function used to initialize the canvas
function initCanvas() {
	//create canvas
    createCanvas(canvasWidth, canvasHeight);
}

function setup() {
	initVars();
	initCanvas();
}

function draw() {
	background(0); //update background
	drawAllNodes();
}

Final Project – Shan Wang – “Slime’s Christmas”

slime's christmas

screenshot from my game

sketch
For the final project, I mainly followed my initial design of the game similar to doodle jump, but with different features and user interface.

var platforms = [];
var allSplashes = [];
var newSplash;
var mode = "START";

var bgColor1;
var bgColor2;

var dropSpeed = 1;
const PF_THINKNESS = 7;
const GRAVITY = 1.5;
const FALLING_INTERV = 50;

var character;
var topPlatform;
var charCurrentPF;

var fallDistance = 0;
var initJump = true;

var aX;
var aY;
var xFactor = 0.3;
var yFactor = 0.15;
var timeFactor = 10;
var distance;
var numberHitted = 0;
var totalScore = 0;

//sound variables
var bgMusic;
var bellSound;

//graphic elements
var snowflakeLinks = [
    "http://imgur.com/2jZMsr7",
    "http://imgur.com/vKvkHSJ",
    "http://imgur.com/X3pNOx0"
]

var frameFilenames = [];

var snowflakes = [];
var snowflake0;
var snowflake1;
var snowGraphs = [];
var allSnowflakesObjects = [];

var wRuffles = [];

var scaleX;
var scaleY;
var snowPosX;
var snowPosY;



function preload() {
    //load sounds
    bgMusic = loadSound("https://courses.ideate.cmu.edu/15-104/f2016/wp-content/uploads/2016/12/bgMusic.wav");
    bellSound = loadSound("https://courses.ideate.cmu.edu/15-104/f2016/wp-content/uploads/2016/12/bellSound.wav");

    //load graphs for snowfaleks
    for (var i = 0; i < snowflakeLinks.length; i++){
        var snowLink = loadImage(snowflakeLinks[i]);
        snowGraphs.push(snowLink);
    }

    var slime = "frames/slime.gif";
    gifSlime = loadGif(slime);


}


function gradient(x,y,wid,hei,c1,c2){
    noFill();
    for (var i = y; i<y+hei; i++){
        var inter = map(i,y,y+hei,0,1);
        var col = lerpColor(c1,c2,inter);
        stroke(col);
        line(x,i,x+wid,i);
    }
}


function makeWaterRuffle(gx, gy, gr, color, alpha){
    var ruffle = {x: gx, y:gy, r:gr, c:color,
                  a: alpha, draw: drawRuffle}
    return ruffle;
}

function drawRuffle(){
    if (this.a >= 0){
        noStroke();
        fill(this.c, this.c, this.c, this.a);
        ellipse(this.x, this.y, this.r, this.r);
    }
}


function makeCharac(cx, cy, color, speedX, speedY){
    var character = {x: cx, y: cy, col: color, vx: speedX, vy: speedY,
                     g: GRAVITY, draw: drawCharac};
    return character;
}

function drawCharac(){
    fill(this.col);
    image(gifSlime, this.x, this.y);
    //ellipse(this.x, this.y, this.r, this.r);
    // idx = frameCount%3;
    // img = frames[idx];
}

function makePlatform(px, py, pw, pc, pt, type) {
    var platform = {x: px, y:py,
                    wid:pw, color:pc,
                    hei: pt, tp: type,
                    draw: drawPlatform};
    return platform;
}

function drawPlatform(){
    fill(this.color);
    noStroke();
    rect(this.x, this.y, this.wid, this.hei);
}

function isTooClose(y){
    for (var i=0; i<platforms.length; i++){
        if (Math.abs(platforms[i].y - y)<20 ){
            return true;
        }
    }
    return false;
}

// check for collision
function hitThePlatform(platform){
    if (collideRectRect(platform.x, platform.y, platform.wid, platform.hei,
        character.x+5, character.y+5, gifSlime.width-5, gifSlime.height-5)){
            return true;
        }
    return false;
}


function makeSplashes(sx, sy, number, bRadius,indiviRadius, initColor, alpha){
    var splash = {x: sx, y:sy, num: number,bigR: bRadius, r: indiviRadius,
                    color: initColor, a: alpha, draw: drawSplashes};
    return splash;
}

function drawSplashes(){
    push();
    translate(this.x, this.y);
    fill(this.color, this.color, this.color, this.a);
    for (var i = 0; i<this.num+1; i++){
        ellipse(0,-this.bigR, this.r, this.r);
        rotate(360/this.num);
    }
    pop();
}

function makeSnowflakes(image, sx, sy, scaleX, scaleY){
    var snowflake = {img: image, x: sx, y: sy, sX:scaleX, sY: scaleY,
                     draw: drawSnowflakes};
    return snowflake;
}

function drawSnowflakes(){
    image(this.img,this.x, this.y,this.img.width*this.sX,this.img.height*this.sY);
}

function setup() {
    //frameRate(50);
    //loop through background music
    bgColor1 = color(190,0,16);
    bgColor2 = color(83,0,0);
    bgMusic.loop();
    createCanvas(600, 800);
    //make water ruffle patter
    for (var i = 0; i < 8; i++){
        var ranX = random(width);
        var ranY = random(height);
        var rndRuffle = makeWaterRuffle(ranX, ranY, random(30,50),random(220,255), random(50, 150));
        wRuffles.push(rndRuffle);
    }

    //make 8 snowflakes with random selection for initial condition
    for (var i = 0; i < 15; i++){
        var rndSnowflake = random(snowGraphs);
        snowflakes.push(rndSnowflake);
    }

    //render snowflakes; make them into objects;
    for (var i = 0; i < snowflakes.length; i++){
        snowflakes[i].loadPixels();
        snowPosX = random(10, width - 10);
        snowPosY = random(10, height - 10);
        scaleX = random(0.1, 0.4);
        scaleY = scaleX;
        var newSnow = makeSnowflakes(snowflakes[i], snowPosX, snowPosY, scaleX, scaleY);
        allSnowflakesObjects.push(newSnow);
    }

    // make platforms
    var counter = 0;
    //make 8 platforms that do not collide with each other
    while (counter < 8){
        var ranPosX, ranPosY, ranWidth;
        do {
            ranPosX = random(80, width-80);
            ranPosY = random(0, height/2-40);
            ranWidth = random(20, 60);
        } while (isTooClose(ranPosY));
        var newPF = makePlatform(ranPosX, ranPosY,ranWidth, 255,PF_THINKNESS, counter);
        var newShadow = makePlatform(ranPosX + 10, ranPosX + 10, ranWidth, 255,PF_THINKNESS, counter);
        platforms.push(newPF);
        //shadows.push(newShadow);
        counter += 1;
    }
    character = makeCharac(width/2, height - gifSlime.height, 155, 0,0);
}



function draw() {
    if (mode == "START"){
        textAlign("CENTER");
        textSize(23);
        textFont("Andale Mono");
        text("Slime's Christmas", width/2-30, height/4);
        line(width/2, height/2, width/2 + 100, height/2);
        textSize(15);
        text("Start Now!", width/2, height/2);
    }

    else if (mode == "GAME" || mode == "christmasInit"){
        gradient(0,0,width,height,bgColor1,bgColor2);
        //image(gifBird, -150,0, gifBird.width*0.9, gifBird.height);
        for (var i = 0; i < wRuffles.length; i++){
            wRuffles[i].r += 1;
            wRuffles[i].a -= 1;
            if (wRuffles[i].a < 0){
                wRuffles.splice(i,1);
            }
        }
        if (wRuffles.length < 10){
            var ranX = random(width);
            var ranY = random(height);
            var rndRuffle = makeWaterRuffle(ranX, ranY, random(30,50),random(220,255), random(50, 150));
            wRuffles.push(rndRuffle);
        }
        for (var i = 0; i < wRuffles.length; i++){
            wRuffles[i].draw();
        }

        for (var i = 0; i < allSplashes.length; i++){
            allSplashes[i].bigR += 3;
            allSplashes[i].a -= 5;
            allSplashes[i].draw();
        }

        for (var i = 0; i < allSnowflakesObjects.length; i++){
            allSnowflakesObjects[i].y += random(dropSpeed*2, dropSpeed*2.5);
            allSnowflakesObjects[i].draw();
            if (allSnowflakesObjects[i].y > height){
                allSnowflakesObjects.splice(i,1);
            }
            if (character.y < height/2){
                allSnowflakesObjects[i].y += 1;
            }
        }

        // set limit of speed on y direction for the character
        fallDistance += dropSpeed;
        if (character.vy > 30){
            character.vy = 30;
        } else if (character.vy < -30){
            character.vy = -30;
        }

        // move platforms & remove those that fall out of canvas
        for (var i = 0; i < platforms.length; i++) {
            platforms[i].y += dropSpeed;
            platforms[i].draw();
            if (platforms[i].y > height){
                platforms.splice(i,1);
                }
        }

        // add new platforms when the old ones drop FALLING_INTERV pixels;
        if (fallDistance % FALLING_INTERV == 0){
            addNewPlatforms();
        }
        // add new snowflakes as needed
        if (allSnowflakesObjects.length < 15){
            addNewSnowFlakes();
        }

        // after first jump, control the velocity on both x and y direction with GRAVITY
        // to simulate the jumping and falling condition
        if (initJump == false){
            distance = mouseX - character.x;
            aY = GRAVITY;
            character.vy += aY*yFactor;
            character.x += distance/timeFactor;
            character.y += character.vy;
        }

        // check if the player hit the platform; keeping track of scores
        if (platforms.length != 0){
            for (var i = 0; i < platforms.length; i++){
                if (hitThePlatform(platforms[i])){
                    numberHitted += 1;
                    totalScore += numberHitted*10;
                    bellSound.play(0,1,1);
                    character.vy = -8;
                    // make splashes when the player hits the platform
                    newSplash = makeSplashes(platforms[i].x + platforms[i].wid/2,
                        platforms[i].y + platforms[i].hei, 10, 50, 6, 255, 100);
                    allSplashes.push(newSplash);
                    //remove platforms that have been hit by players
                    platforms.splice(i,1);
                }
            }
        }
        // adjust the positions of the platforms when the player jumps
        // higher than half of the canvas
        for (var i = 0; i < platforms.length; i++){
            if (character.y < height/2){
                platforms[i].y +=1;
            }
        }

        // bounce the player back to the canvas if the player goes off the side
        if (character.x > width & 0 < character.y < height){
            character.x = character.r;
        } else if(character.x < 0 & 0 < character.y < height){
            character.x = width - character.r;
        } else if (character.y > height){
            mode = "GAMEOVER"
            bgMusic.stop();
        }
        character.draw();

    }
    else if (mode == "GAMEOVER"){
        gradient(0,0,width,height,bgColor1,bgColor2);
        fill(255);
        textSize (30);
        textAlign(CENTER);
        textFont("Andale Mono");
        text("GAME OVER!", width/2, height/2);
        textSize (15);
        text("The Steps You Jumped: " + numberHitted, width/2, height*2/3);
        text ("Total Score: " + totalScore, width/2, height*3/4);
        textSize (10);
        text("Press R to restart the game", width/2, height*5/6);
    }
}

function addNewPlatforms(){
    var newX = random(40, width-40);
    var ranWid = random(40, 65);
    var newPlatForm = makePlatform(newX, 0, ranWid, 255, PF_THINKNESS);
    platforms.push(newPlatForm);
}


function addNewSnowFlakes(){
    var addedSnow = random(snowflakes);
    addedSnow.loadPixels();
    snowPosX = random(10, width - 10);
    scaleX = random(0.1, 0.4);
    scaleY = scaleX;
    var newSnow = makeSnowflakes(addedSnow, snowPosX, 0, scaleX, scaleY);
    allSnowflakesObjects.push(newSnow);
}

function mouseClicked(){
    if (mode == "START"){
        if (collidePointRect(mouseX, mouseY, width/2, height/2-10, 80, 30)){
            mode = "christmasInit";
        }
    }
    else if (mode == "christmasInit"){
        character.vy = -8;
        if (initJump == true){
            initJump = false;
            mode = "GAME";
        }
    }
}

function keyTyped(){
    // reset the game to the initial status
    if (key == "r"|| key == "R"){
        mode = "christmasInit";
        platforms = [];
        allSplashes = [];
        snowflakes = [];
        allSnowflakesObjects = [];
        wRuffles = [];
        numberHitted = 0;
        totalScore = 0;
        setup();
        initJump = true;
    }
}

Different from the existing game, the platforms in my “Slime’s Christmas” will disappear if hit by the character. And the “jumping” of the slime, which follows the mouse, is simulated with gravity to give a sense of physical reality.

With what we learned in object oriented programming, I also created effect of random water ruffle and splashes that are generated at the position of the hit platform.

 

 

All music downloaded from freesound.org

The slime gif credited to google image.

 

mreyes – final project

screen-shot-2016-12-10-at-12-07-15-am

Please download the files and play the game though local server. I tried uploading the files to both wordpress and the andrew webite that students are given but, neither work.

This project is a continuation of project that I did in a previous class and wanted to expand on. Roger signed off on this agreeing that I would make it clear what was pre-made. ONLY the audio and mic input functions are new. Everthing esle was made preiviously. I have also sectioned off and uncommented the code that is not new and marked it “Pre-made DO NOT GRADE”.

This added in audio function is an exploration on simple machine learning. For a little while I was trying to use recordings and slice those recordings into arrays to make the audio. But this proved too dificult for my skill level and also did not really achive the effect I wanted. So instead how the program works is that there is a very sensative volume monitor analyzing input from the mic and then depending on how loadly you talk (or sing or hum or what ever) the program puts in diffrent sound files.

As I said the monitor is very sensative and the game it ment to be a little dificult. A simple cheet that I’ve found is that singing or humming work better then actually talking.

sketch

//Pre-made DO NOT GRADE
///////////////////////////////////
var background_sound;
var end_sound;
var bgs;
var bgi;
var character;
var feed;
var clean;
var talk;
var ending1 = false;
var ending2 = false;
var hunger = 3;
var MAX_HUNGER = 10; 
var dirty = 3;
var MAX_DIRTY = 10;
var purity = 10
var MAX_PURITY = 20  
var volume = 0;
var mic;
var pixelScale = 4;
var idle_animation;
var play_animation;
var board_animation;
var barf_animation;
var die_animation;   
var dirty_animation;
var clean_animation;
var tooClean_animation;
var feed_icon;
var feed_icon_roll;
var fire_image
var house_image;
////////////////////////////////

//sound variables
var play_sound;
var barf_sound;
var hunger_sound;
var chat_sound;
var tooLoud_sound;
var ah_sound;
var eee1_sound;
var eee2_sound;
var talk_sound;
var haEh_sound;
var nahnah_sound;
var hello_sound;
var no_sound; 
var nonono_sound;
var yes_sound;
var playCleanHouse_sound;
var help_sound;
var look_sound;
var tooMuch_sound;
var stop_sound;
var good_sound;
var pleaseHelp_sound;
var thankYou_sound;
var whatIs_sound;
var stopIt_sound;
var youAre_sound;
var iNeedYou_sound;
var doYou_sound;
var clean2_sound;
var fun_sound;
var thisFeels_sound;
var thisIs_sound;
var who_sound; 
var tooClean_sound;
var Clean_sound;

//variables that will keep track of how sounds files change
var talk = 0
var talkIncrease = .01 
var MAX_TALK = 10
    
function preload() {

//Pre-Made DO NOT GRADE
////////////////////////////////////////////////////////////////////
  background_sound = loadSound("assets/bg.mp3");
  end_sound = loadSound("assets/end.mp3");
  sprite_sheet = loadSpriteSheet('assets/idle.png', 65, 65, 48);
  idle_animation = loadAnimation(sprite_sheet);
  sprite_sheet = loadSpriteSheet('assets/play.png', 65, 65, 60);
  play_animation = loadAnimation(sprite_sheet);
  sprite_sheet = loadSpriteSheet('assets/board.png', 65, 65, 12);
  board_animation = loadAnimation(sprite_sheet);
  sprite_sheet = loadSpriteSheet('assets/lazer.png', 65, 65, 23);
  barf_animation = loadAnimation(sprite_sheet);
  sprite_sheet = loadSpriteSheet('assets/clean.png', 65, 65, 37);
  clean_animation = loadAnimation(sprite_sheet);
  sprite_sheet = loadSpriteSheet('assets/tooClean.png', 65, 65, 44);
  tooClean_animation = loadAnimation(sprite_sheet);
  sprite_sheet = loadSpriteSheet('assets/dirty.png', 65, 65, 21);
  dirty_animation = loadAnimation(sprite_sheet);
  bg_image = loadImage("assets/bg.png");
  end_image = loadImage("assets/end.png");
  fire_image = loadImage("assets/fire.png");
  house_image = loadImage("assets/house.png");
  feed_icon = loadImage("assets/feed_button.png");
  feed_icon_roll = loadImage("assets/feed_button_roll.png");
  clean_icon = loadImage("assets/feed_button.png");
  clean_icon_roll = loadImage("assets/feed_button_roll.png");
  talk_icon = loadImage("assets/feed_button.png");
  talk_icon_roll = loadImage("assets/feed_button_roll.png");
  idle_animation.frameDelay = 8;
  play_animation.frameDelay = 12;
  tooClean_animation.frameDelay = 12;
  clean_animation.frameDelay = 8
/////////////////////////////////////////////////////////////////

//load sound
  eat_sound = loadSound("assets/eat.wav");
  barf_sound = loadSound("assets/barf.wav");
  hunger_sound = loadSound("assets/chirp.wav");
  die_sound = loadSound("assets/die.wav");
  tooLoud_sound = loadSound("assets/tooLoud.wav");
  chat_sound = loadSound("assets/chat.wav");
  ah_sound = loadSound("assets/ah.mp3");
  eee1_sound = loadSound("assets/eee1.wav");
  eee2_sound = loadSound("assets/eee2.mp3");
  talk_sound = loadSound("assets/talk.wav");
  haEh_sound = loadSound('assets/haEh.mp3');
  nahnah_sound = loadSound('assets/nahnah.mp3');
  hello_sound = loadSound('assets/hello.mp3');
  no_sound = loadSound('assets/no.mp3');
  nonono_sound = loadSound('assets/nonono.mp3');
  yes_sound = loadSound('assets/yes.mp3');
  playCleanHouse_sound = loadSound('assets/playCleanHouse.mp3');
  help_sound = loadSound('assets/help.mp3');
  look_sound = loadSound('assets/look.mp3');
  tooMuch_sound = loadSound('assets/tooMuch.mp3');
  stop_sound = loadSound('assets/stop.mp3');
  good_sound = loadSound('assets/good.mp3')
  pleaseHelp_sound = loadSound('assets/pleaseHelp.mp3');
  thankYou_sound = loadSound('assets/thankYou.mp3');
  whatIs_sound = loadSound('assets/whatIs.mp3');
  stopIt_sound = loadSound('assets/stopIt.mp3');
  youAre_sound = loadSound('assets/youAre.mp3');
  iNeedYou_sound = loadSound('assets/iNeedYou.mp3')
  doYou_sound = loadSound('assets/doYou.mp3');
  clean2_sound = loadSound('assets/clean.mp3');
  fun_sound = loadSound('assets/fun.mp3');
  thisFeels_sound = loadSound('assets/thisFeels.mp3');
  thisIsFun_sound = loadSound('assets/thisIsFun.mp3');
  who_sound = loadSound('assets/who.mp3');
  tooClean_sound = loadSound("assets/tooClean.wav")
  clean_sound = loadSound("assets/Clean.wav");
      
}

function setup() {

//set up mic input  
  mic = new p5.AudioIn();
  mic.start(); 

//Pre-Made DO NOT GRADE
////////////////////////////////////////////////////////////////////
  var canvas = createCanvas(150, 150);
  bgs = background_sound.play(); 
  background_sound.loop();    
  canvas.style("width", width * pixelScale + "px");
  canvas.style("height", height * pixelScale + "px");
  noSmooth();
  bgi = createSprite(width/2,(height/2)-3,150,145);
  character = createSprite(77, 41, 65, 65);
  character.addAnimation('idle', idle_animation);
  character.addAnimation('play', play_animation);
  character.addAnimation('board', board_animation);
  character.addAnimation('barf', barf_animation);
  character.addAnimation('clean', clean_animation);
  character.addAnimation('tooClean', tooClean_animation);
  character.addAnimation('dirty', dirty_animation); 
  character.addAnimation('fire',fire_image);
  character.addAnimation('house',house_image);  
  bgi.addAnimation("bg",bg_image);
  bgi.addAnimation("end",end_image);
  feed = createSprite(4, 32, 4, 4);
  clean = createSprite(18, 32, 4, 4);
  feed.addImage(feed_icon);
  clean.addImage(feed_icon);
////////////////////////////////////////////////////////////////////

//Pre-Made DO NOT GRADE
////////////////////////////////////////////////////////////////////
feed.onMousePressed = function() {

  if (character.getAnimationLabel() == "idle" || character.getAnimationLabel() == "board") {
    if(purity <= 0){
      bgs = end_sound.play();
      bgi.changeAnimation("end");
      character.changeAnimation("fire");
      character.animation.rewind();
      ending1 = true
      feed.remove();
      clean.remove();
  }
        
    if(purity >= MAX_PURITY){
      bgs = end_sound.play();
      bgi.changeAnimation("end");
      character.changeAnimation("fire");
      character.animation.rewind();
      ending2 = true
      feed.remove();
      clean.remove();
    }
  
  hunger -= 4;
  purity += 1

    if (hunger >= 0 ) {
      character.changeAnimation("play");
      character.animation.rewind();
      eat_sound.play();
    } 

    if (hunger <= 0) {
      hunger = 0;
      purity -=5
      character.changeAnimation("barf");
      character.animation.rewind();
      barf_sound.play();
    }
  }
}

feed.onMouseOver = function() {
  feed.addImage(feed_icon_roll);
}

feed.onMouseOut = function() {
  feed.addImage(feed_icon);
}
clean.onMousePressed = function() {

  if (character.getAnimationLabel() == "idle" || character.getAnimationLabel() == "dirty") {
    if(purity <= 0){
      bgs = end_sound.play();
      bgi.changeAnimation("end");
      character.changeAnimation("fire");
      character.animation.rewind();
      ending1 = true
      feed.remove();
      clean.remove();
    }
        
    if(purity >= MAX_PURITY){
      bgs = end_sound.play();
      bgi.changeAnimation("end");
      character.changeAnimation("fire");
      character.animation.rewind();
      ending2 = true
      feed.remove();
      clean.remove();
    }

  dirty-= 1;
  purity += 1

    if (dirty >= 0){
      character.changeAnimation("clean");
      character.animation.rewind();
      clean_sound.play();
    } 

    if (dirty <= 0){
      purity -=5
      dirty = 0;
      character.changeAnimation("tooClean");
      character.animation.rewind();
      tooClean_sound.play();
    }
  }
}

clean.onMouseOver = function() {
  clean.addImage(feed_icon_roll);
}

clean.onMouseOut = function() {
    clean.addImage(feed_icon);
}


}
////////////////////////////////////////////////////////////////////

function draw() {

  var v = mic.getLevel(); //get volume of mic
  volume += (v-volume)/3; //smooth out reading of volume
  var micMap = map(volume, 0, 1, 10, 100); // map volume

  if(ending1 == false || ending2 == false){ //only activate if endings are false 
      
    if(talk <= 0){ // set when to change sound
      //if mic is less than 30 then uncofertable sound plays and purity goes down
      if (micMap >= 30 ){ 
        purity -= .1
        eee1_sound.play();
      }
      //if between 20 and 30 then chat souns play 
      if (micMap > 20 & micMap < 30 ){
        talk_sound.play();
      //talk increase when talk to it softly 
      if(talk <=MAX_TALK){
          talk += talkIncrease
        }
      }
    }

  //repeat similar set up for 9 more levels

    if(talk <= 1 & talk > 0){
  
      if (micMap >= 30 ){
        purity -= .1
        eee1_sound.play();
      }
     
      if (micMap > 20 & micMap < 30 ){
      
        chat_sound.play();

        if(talk <=MAX_TALK){
          talk += talkIncrease
        }
      }
    }

    if(talk <= 2 & talk > 1){
      hunger_sound = ah_sound

      if (micMap >= 30 ){
        purity -= .1
        eee2_sound.play();
      }
     
      if (micMap > 20 & micMap < 30 ){
        ah_sound.play();

        if(talk <= MAX_TALK){
          talk += talkIncrease
        } 
      }
    }

    if(talk <= 3 & talk > 2){
      hunger_sound = nahnah_sound

      if (micMap >= 30 ){
        purity -= .1
        nahnah_sound.play();
      }
     
      if (micMap > 20 & micMap < 30 ){
        haEh_sound.play();

        if(talk <= MAX_TALK){
        talk += talkIncrease
        }
      }
    }

    if(talk <= 4 & talk > 3){
      hunger_sound = no_sound;
      clean_sound = yes_sound;
      eat_sound = yes_sound;
      tooClean_sound =  nonono_sound;

      if (micMap >= 30 ){
        purity -= .1
        nonono_sound.play();
      }
     
      if (micMap > 20 & micMap < 30 ){
        hello_sound.play();

        if(talk <= MAX_TALK){
        talk += talkIncrease
        }
      }
    }

    if(talk <= 5 & talk > 4){
      hunger_sound = stop_sound;
      clean_sound = yes_sound;
      eat_sound = yes_sound;
      tooClean_sound =  nonono_sound;

      if (micMap >= 30 ){
        purity -= .1
        nonono_sound.play();
      }
     
      if (micMap > 20 & micMap < 30 ){
      playCleanHouse_sound.play();
        
        if(talk <= MAX_TALK){
            talk += talkIncrease
        }
      }
    }

    if(talk <= 6 & talk > 5){
      hunger_sound = help_sound;
      clean_sound = good_sound;
      eat_sound = good_sound;
      tooClean_sound = tooMuch_sound;

      if (micMap >= 30 ){
        purity -= .1
        tooMuch_sound.play();
      }
     
      if (micMap > 20 & micMap < 30 ){
          look_sound.play();

        if(talk <= MAX_TALK){
            talk += talkIncrease
        }
      }
    }

    if(talk <= 7 & talk > 6){
      hunger_sound = pleaseHelp_sound;
      clean_sound = thankYou_sound;
      eat_sound = thankYou_sound;
      tooClean_sound = tooMuch_sound;

      if (micMap >= 30 ){
        purity -= .1
        tooMuch_sound.play();
      }
     
      if (micMap > 20 & micMap < 30 ){
        whatIs_sound.play();

        if(talk <= MAX_TALK){
          talk += talkIncrease
        }
      }
    }

    if(talk <= 7 & talk > 6){
      hunger_sound = pleaseHelp_sound;
      clean_sound = clean2_sound;
      eat_sound = fun_sound;
      tooClean_sound = tooMuch_sound;

      if (micMap >= 30 ){
        purity -= .1
        stopIt_sound.play();
      }
     
      if (micMap > 20 & micMap < 30 ){
        whatIs_sound.play();
        
        if(talk <= MAX_TALK){
        talk += talkIncrease
        }
      }
    }


    if(talk <= 8 & talk > 7){
      hunger_sound = iNeedYou_sound;
      clean_sound = thisFeels_sound;
      eat_sound = thisIsFun_sound;
      tooClean_sound = stopIt_sound;

      if (micMap >= 30 ){
        purity -= .1
        youAre_sound.play();
      }
     
    if (micMap > 20 & micMap < 30 ){
      doYou_sound.play();

      if(talk <= MAX_TALK){
        talk += talkIncrease
      }
    }
  }

  if(talk > 8){
    hunger_sound = iNeedYou_sound;
    clean_sound = thisFeels_sound;
    eat_sound = thisIsFun_sound;
    tooClean_sound = stopIt_sound;

    if (micMap >= 30 ){
      purity -= .1
      youAre_sound.play();
    }
     
    if (micMap > 20 & micMap < 30 ){
      who_sound.play();

      if(talk <= MAX_TALK){
        talk += talkIncrease
      }
    }
  }
}

//Pre-Made DO NOT GRADE
////////////////////////////////////////////////////////////////////   
  background(0);
  print(talk)

  if(frameCount % 800 == 0)
  {

    if(hunger<MAX_HUNGER){
      hunger+=2;
    }
          
    if(dirty<MAX_DIRTY){
      dirty+=1;
    }
        
    if((hunger>8 & ending1 == false) || (dirty>=MAX_DIRTY && ending2 == false)){ 
       character.changeAnimation("board");
        hunger_sound.play();
    }
        
    if((dirty>8 & ending1 == false) || (dirty>=MAX_DIRTY && ending2 == false)){
      character.changeAnimation("dirty");
      hunger_sound.play();
          }
        
    if((hunger>=MAX_HUNGER & ending1 == false)|| (dirty>=MAX_DIRTY && ending2 == false)){
      purity -=5
    }
        
    if((dirty>=MAX_DIRTY && ending1 == false) || (dirty>=MAX_DIRTY && ending2 == false)){
      purity -=5
    }

  }
      

    if (character.getAnimationLabel() == "play" && character.animation.getFrame() == character.animation.getLastFrame()) {
      character.changeAnimation("idle");
    }
      
    if (character.getAnimationLabel() == "barf" & character.animation.getFrame() == character.animation.getLastFrame()) {
      character.changeAnimation("idle");
    }
      
    if (character.getAnimationLabel() == "clean" & character.animation.getFrame() == character.animation.getLastFrame()) {
      character.changeAnimation("idle");
    }

    if (character.getAnimationLabel() == "tooClean" & character.animation.getFrame() == character.animation.getLastFrame()) {
      character.changeAnimation("idle");
    }

    drawSprites();
    
    {
    if(ending1 == false & ending2 == false){
      noStroke()
      textSize(5);
      fill(60);
      var rectangleLength = map(hunger, 0, MAX_HUNGER, 0, 20);
      rect(9,30,3,floor(rectangleLength));
      text('play',2, 25);
      
      var rectangleLength = map(dirty, 0, MAX_DIRTY, 0, 20);
      rect(22,30,3,floor(rectangleLength));
      text('clean',18, 25);
      
      var rectangleLength = map(micMap, 0, 50, 0, 20);
      text('volume', 40, 83);
      rect(40, 85,floor(rectangleLength),3);

      fill(255);
      var rectangleLength = map(purity, 0, MAX_PURITY, 0, 20);
      rect(125,30,5,floor(rectangleLength));
      text('purity', 125,25);
      }
      
      if (ending1 == true){
      character.changeAnimation("fire");
      noStroke();
      fill(255);
      textSize(6);
      textAlign(CENTER);
      text("it's free. it's made it's jugement. everything is gone.",width/2, height*.75);
      }
      
      if (ending2 == true){
      character.changeAnimation("house");
      noStroke();
      fill(255);
      textSize(6);
      textAlign(CENTER);
      text("finaly. its free. the world can now be pure.",width/2, height*.75);
      }
      
      }
      
    }
/////////////////////////////////////////////////////////////////////////////////////////////
    
    
  

Final Project Lydia Jin – Piano Keys for Beginners

//Lydia Jin
//jialuj@andrew.cmu.edu
//Section D
//Final Project

//define necessary variables
var piano = [];
var alphabet = ['a', 's', 'd', 'f', 'g', 'h', 'j'];
var alphabet2 = ['A', 'S', 'D', 'F', 'G', 'H', 'J'];
var ASSETS_DIR = "assets/";
var POSTFIX = "-piano.wav"
var amp;
var hz;
var rec = [];
var w;
var buffer;
var button1, button2, button3, button4, button5, button6, button7;
var colorNum = 0;
var bgm1, bgm2, bgm3; //BGM stands for background metronome 
var mic, recorder, soundFile;
var state = 0;

var soundLinks = ["https://courses.ideate.cmu.edu/15-104/f2016/wp-content/uploads/2016/12/0-piano.wav",
                "https://courses.ideate.cmu.edu/15-104/f2016/wp-content/uploads/2016/12/1-piano.wav",
                "https://courses.ideate.cmu.edu/15-104/f2016/wp-content/uploads/2016/12/2-piano.wav",
                "https://courses.ideate.cmu.edu/15-104/f2016/wp-content/uploads/2016/12/3-piano.wav",
                "https://courses.ideate.cmu.edu/15-104/f2016/wp-content/uploads/2016/12/4-piano.wav",
                "https://courses.ideate.cmu.edu/15-104/f2016/wp-content/uploads/2016/12/5-piano.wav",
                "https://courses.ideate.cmu.edu/15-104/f2016/wp-content/uploads/2016/12/6-piano.wav"];



for (var i = 0; i < 7; i++){
    //push keys into the array 
    piano[i] = new KeyStroke(alphabet[i], alphabet2[i]);

}

function setup() {
    createCanvas(600, 200);
    amp = new p5.Amplitude();
    hz = new p5.FFT(0, 256);
    w = width/256;
    colorMode(HSB);
    angleMode(DEGREES);
    
    //create button for BGM 40
    button1 = createButton('40 BPM');
    button1.position(543,40);
    button1.mousePressed(PlayBGM1);

    //create button for BGM 50
    button2 = createButton('50 BPM');
    button2.position(543,64);
    button2.mousePressed(PlayBGM2);

    //create button for BGM 60
    button3 = createButton('60 BPM');
    button3.position(543,88);
    button3.mousePressed(PlayBGM3);

    //create button for no background metronome
    button4 = createButton('No BGM');
    button4.position(541,112);
    button4.mousePressed(ResetBGM);

    //create button for recording
    button5 = createButton('Record');
    button5.position(545,136);
    button5.mousePressed(RecordAudio);

    //create button for playing recording
    button6 = createButton('Play');
    button6.position(562,160);
    button6.mousePressed(PlayAduio);
    button6.hide();

    //create button for saving recording
    button7 = createButton('Save');
    button7.position(557,184);
    button7.mousePressed(SaveRecord);
    button7.hide();

    //create recorded soundfile
    recorder = new p5.SoundRecorder();
    recorder.setInput();
    soundFile = new p5.SoundFile();

    
}

//helper function for playing BGM1
function PlayBGM1(){
    bgm2.stop();
    bgm3.stop();
    bgm1.loop();
}

//helper function for playing BGM2
function PlayBGM2(){
    bgm1.stop();
    bgm3.stop();
    bgm2.loop();
}

//helper function for playing BMG3
function PlayBGM3(){
    bgm1.stop();
    bgm2.stop();
    bgm3.loop();
}

//helper function for no BGM
function ResetBGM(){
    bgm1.stop();
    bgm2.stop();
    bgm3.stop();
}

//helper function to record audio
function RecordAudio(){
    if (state == 0 ){
        recorder.record(soundFile);
        state ++;
    }
    else if (state = 1){
        recorder.stop();
        state++;
    }
  
}

//helper function to play recording
function PlayAduio(){
    soundFile.play();
}

//helper function to download recording
function SaveRecord(){
    saveSound(soundFile, 'mySound.wav');
}
    


function draw() {
    noStroke();
    background('black');

    //draw buttons
    fill('white');
    textSize(13);
    noStroke();
    text('Metronome', 535, 15);
    text('Rhythms', 543, 27);
    
    //hide buttons
    if (state === 0) {
        button6.hide();
        button7.hide();
        //state++;
    }

    else if (state === 1) {
        //display instructing text
        text('Recording! Click Record Again to stop.', 150, 20);
    }

    else if (state === 2) {
        
        if (soundFile.isPlaying() == true){
            button6.hide();
            bgm1.stop();
            bgm2.stop();
            bgm3.stop();
            //display text
            text('Playing...', 250, 20);

        }
        else{
            button5.hide();
            //show buttons after recording is done
            button6.show();
            button7.show(); 
            text('Recording stopped! Chose to play or save. Refresh the page to start a new recording.', 20, 20);
        }
    }


    //draw keyboard letters
    for (var i = 0; i < 7; i++){

        push();
        textSize(25);
        stroke('white');
        fill('white');
        text(alphabet2[i], i* (width - 70)/7 + (width - 70)/14, 195); 
        pop();


    }
    
    //draw displays
    if (state != 0){
        push();
        var level = amp.getLevel();
        rec.push(level);
        stroke('white');
        noFill();
        var cy = map(level, 0 , 1, height, 0);
        translate(0, height/2 - cy);
        beginShape();
        colorNum++;
        if (colorNum > 255){
                colorNum = 0;
            }
        for (var i = 0; i < rec.length; i++){
            var y = map(rec[i], 0 , 1, height, 0);
            stroke(colorNum, 255, 255);
            vertex(i, y);
        }
        endShape();

        if (rec.length > width - 70){
            rec.splice(0, 1);
        }
        pop();

        push();
        stroke('red');
        line(rec.length, 0, rec.length, height);
        pop();
    }
    //display amplitude with rectangles
    var spectrum = hz.analyze();
    noStroke();
    for (var i = 0; i < spectrum.length; i++){
        var amp1 = spectrum[i];
        var y = map(amp1, 0, 256, height, 0);
        fill(i, 255, 255);
        if (soundFile.isPlaying() == true){
            rect(i + (width - 90)/2, y , w - 2, height - y);
        }
        else{
            rect(i + buffer, y , w - 2, height - y);
        }
    }

}


function preload(){
    //preload sound files 
    for (var i = 0; i < piano.length; i++){
        piano[i].sound = loadSound(soundLinks[i]);

    }
    //store sound files to variables 
    bgm1 = loadSound("https://courses.ideate.cmu.edu/15-104/f2016/wp-content/uploads/2016/12/40-BPM.wav");
    bgm2 = loadSound("https://courses.ideate.cmu.edu/15-104/f2016/wp-content/uploads/2016/12/50-BPM.wav");
    bgm3 = loadSound("https://courses.ideate.cmu.edu/15-104/f2016/wp-content/uploads/2016/12/60-BPM.wav");
}



function KeyStroke(LKey, CKey){
    var sound;
    //lower case keys
    this.LKey = LKey;
    //upper case keys
    this.CKey = CKey;
}

function keyPressed(){
    
    if (state === 0 & key === 'space') {

        state++;
    }
    for (var i = 0; i < piano.length; i++){
        if ((key === piano[i].LKey) || (key === piano[i].CKey)){
            piano[i].sound.play();
            
            buffer = i*80;
            fill('orange');
            rect(i*width/7, 170, width/7, 30);
        }

    }
}

My program is designed for kids or beginners who don’t have any musical background in the goal of getting them to know the 7 basic keys in piano with the aid of a metronome. This program is simple to use and should build interest in users because they get to record what they played and replay or download the recordings. Users can follow instructions that are displayed in the program to know exactly how to use this program.

Instructions for use:
1. 4 background metronome options: 40 BPM, 50 BPM, 60 BPM or no BPM at all. Press the button to access each. (The buttons are named BGM, which stands for background metronome)
2. Keys A,S,D,F,G,H,J when pressed, will play piano keys A,B,C,D,E,F,G respectively. The code is written in a way that both capital and lower case keyboard keys will work.
3. Record your performance by hitting the record button, once done, hit the record button again to stop recording.
4. After you are finished recording, you have the option to either play your recording or save it. By pressing the save button, your audio recording file will be downloaded to your computer.
5. Refresh the page to start new recording.

Additional features displayed:
1. The line in the middle shows you the amplitude of the sound. The lines changes color for more fun 🙂
2. The rectangles that pop up when sound is played shows you the frequency of the sound.
* These are made possible by using P5js built in sound functions

Notes to be taken into consideration when grading:
1. This is modified from the final proposal. The reason I decided to change this is because I think this program is more practical for users and also has cool features. (Already talked to the professor about the change)
2. The sounds are downloaded from freesound.org
3. The buttons’ scales are off when sketch is embedded on WordPress. The original file did not have overlapping buttons.
4. When running locally, the program only runs when Firefox is used.

Final Project – Vtavarez (“Fireflies”)

For my final project, I created a “capture the fly” type game. I thought that this would be a prototype for a phone screen, hence the attempted phone screen sizing. My inspiration for the game comes from the song “Fireflies” by Owl City. The song is about dealing with insomnia and since I also have trouble sleeping, I thought it would be a good fit to create a pretty boring, softly colored game that people can play to fall asleep.

The mechanics are pretty simple. Here you are waving around a circle using the arrow keys, on a phone, it would be your finger. Your objective is to capture the fireflies that are flickering in the night. As you do so, your “jar/eater” becomes heavier and moves around slower, due to a slower speed function and increased computing use. The slowing is meant to make your movements more slowly and careful as you start drifting into sleep. Additionally, for decoration, the more fireflies you gather, the more that the tree will grow. This serves as a visual indicator of where you are in the game.

Here is a picture of the early stages of the game:

growing-plant

Here is a picture of later stages of the game:

grown-plant

sketch-33.js

//Victor Tavarez
//Secion D
//vtavarez@andrew.cmu.edu
//Final Project


var score = 0;//contains the images for the story board, start with blank
var particles =[];
var trueHeight;
var eaterX;
var eaterY;
var eaterSize=20;
var eaterSpeed = 10;

// draws the "jar that captures fireflies"
function drawJar(){
    fill(200,215,255,200);
    ellipse(eaterX,eaterY, eaterSize,eaterSize);
}
// moves the "jar that captues fireflies"
function moveJar(){
    //move jar within grid
    if (keyIsDown(LEFT_ARROW)&(eaterX-eaterSize/2 > 0)){
        eaterX-=eaterSpeed
    }
    if (keyIsDown(RIGHT_ARROW)&&(eaterX+eaterSize/2 < width)){
        eaterX+=eaterSpeed
    }
    if (keyIsDown(UP_ARROW)&&(eaterY-eaterSize/2 > 0)){
        eaterY-=eaterSpeed
    }
    if (keyIsDown(DOWN_ARROW)&&(eaterY+eaterSize/2 < trueHeight)){
        eaterY+=eaterSpeed
    }
}
//moves allows for the capture of firefly, increases score
function jarCapture(b,px,py){
    var limits  = dist(eaterX,eaterY, px, py);
    if(limits < eaterSize/2){
        score+=1;
        eaterSize+=b.size/4;
        b.x=eaterX;
        b.x=eaterY;
        particles.pop(b);
        if ((score%4) ==0){
            makeParticle(random(0,width),random(0,trueHeight),
                                       random(-10,10), random(-10,0),
                                       random(2,10));
        }
    }
}
//gives firelfies free motion within the space
function moveParticle(){
    this.x += this.dx;
    this.y += this.dy;

    if (mouseX == this.x & mouseY ==this.y){
        this.dx = 0;
        this.dy = 0;
    }
    if (this.x > width) { // bounce off right wall
        this.x = width - (this.x - width);
        this.dx = -this.dx 
    } else if (this.x < 0) { // bounce off left wall
        this.x = -this.x;
        this.dx = -this.dx;
    }
    if (this.y > height-50) { // bounce off bottom
        this.y = (height-50);
        this.dy = -this.dy;
    } else if (this.y < 0) { // bounce off top
        this.y = -this.y;
        this.dy = -this.dy;
    }
    //stop bugs from crawling if they reach a dark spot in underlying image;
}
//draws each individual firefly
function drawParticle(){  
    for(var i=this.size; i > 0; i--){
        //looks like they are flickering
        fill(this.cr,this.cg,this.cb,random(0,100));
        ellipse(this.x,this.y,i+10,i+10);
        fill(this.cr,this.cg,this.cb); 
        ellipse(this.x,this.y,i,i);
    }
}
//births new fireflies
function makeParticle(px,py,pdx,pdy,size){ //generate individual bugs
    var xr = 222;
    var xg = 250;
    var xb = 200;
    b = {x:px, y:py, 
         dx:pdx, dy:pdy, 
         age:0, 
         step: moveParticle, 
         draw: drawParticle, 
         cr:xr,
         cg:xg,
         cb:xb,
         size:size,
     }
    return b;
}
//draws the story board where score and directions are kept.
function drawStoryBox(){
    noStroke();
    fill(80,150,100);
    rect(0,height-50,width,70);//border between story box and canvas
    fill(50,55,55);
    textStyle(BOLD);
    text(score,width-20,height-20);//our button for changing to next page
    
    textAlign(LEFT);
    textSize(12);
    text("Use Arrow Keys to capture the Fireflies.", 10,trueHeight+30)
}
//resents the amount of dragon flies while making the game a little more difficult
function reset(){
    setup();
    eaterSize*=.75; // decrease size by 75%
    eaterSpeed-=1;  // decrease seed
    if (eaterSpeed <= 0){ //absolute reset of game
        setup();
        score=0;
        eaterSize=20;
        eaterSpeed=10;
    }
}

function setup(){
    createCanvas(300,500);
    trueHeight = height-50;
    eaterX = width/2;
    eaterY = trueHeight/2;
    frameRate(35);
    for(var i=0; i < 10; i++){
        var newParticle = makeParticle(random(0,width),random(0,trueHeight),
                                       random(-10,10), random(-10,0),
                                       random(2,10));
        particles.push(newParticle);
    }
}
var angle;
function draw(){
    background(50,60,100)    
    for (var i=0; i < particles.length;i++){
        var b = particles[i];
        b.step();
        b.draw();
        jarCapture(b,b.x,b.y,b.size);
    }

    drawStoryBox();// has the directions to the game
    drawJar();
    moveJar();  
    //reset the setup time you run out of fireflies, after 10 times, game resets
    if (particles.length == 0){
        reset();
    }

    //tree for decorations
    angle = 10*(noise(millis()/4000)-0.5);
    push();
    fill(0);
    translate(width/2, trueHeight+5);
    drawBranch(0, 10);
    pop();  
}
function drawBranch(depth,len) {
    strokeWeight(1)
    stroke(0);
    line(0, 0, 0, -len);
    push();
    translate(0, -len);
    drawTree(depth + 1, len);
    pop();
}
function drawTree(depth,len) {
    if (depth <= score/10){ 
        push();
        rotate(radians(20 + angle));
        drawBranch(depth,len);
        pop();
        push();
        rotate(radians(-10+ angle));
        drawBranch(depth,len);
        pop();
    }
}

 

Hannah K-Final Project

sketch-35.js

var ySpeed = 1;
var countOfEspresso = 0; // Keeps track of how many total espresso shots

// All var for slider
var offset = 0.5;
var barX = offset;
var barY;
var barW;
var barH = 100;
var sliderX = offset;
var sliderY;
var sliderW = 115;
var sliderH = 100;
var modifer = 40;

// Espresso Array
var espresso = [];
var numEspresso = 10; // Initial number of espresso shots

function setup() {
    createCanvas(600, 425);
    for(i = 0; i < numEspresso; i++) {
      var newEspresso = new Espresso();
      espresso.push(newEspresso);
    }
}

function draw() {
    background(175, 238, 238);
    //textAlign("CENTER");
    fill(0);
    textSize(25);
    text("HOW MUCH COFFEE SHOULD YOU DRINK?", 40, 40);

    updateAndDisplayEspresso();
    
    // Area of slider - Same color as background so slider 
    // Is not actually visible
    // Relied on Lab Week 3 to create slider
    noStroke();
    barY=height-98;
    barW=width-2*offset;
    fill(175,238,238);
    rect(barX,barY,barW,barH);

    // Create divider
    stroke(210, 210, 210);
    line(0, barY-1, width, barY-1);
    stroke(0);
    strokeWeight(2);
    textSize(20);
    text("^ Catch before this line! ^", width/2-100, barY+20);

    // Actual slider (Will be the espresso cup in this case)
    noStroke();
    sliderY=barY;
    fill(255);
    rect(sliderX, sliderY, sliderW, sliderH);


    // The following lines of help to create the cup shape
    fill(175,238,238);
    triangle(sliderX, barY, sliderX + 20, barY + 100, sliderX, barY + 100);
    triangle(sliderX + 115, barY, sliderX + 115, barY + 100, 
    sliderX + 95, barY + 100);
    fill(220,220,220);
    rect(sliderX + 18, sliderY + 90, 79, 8);
    fill(100);
    text("Score: " + countOfEspresso, width/2-20, height-20);

    // Terminating the program
    // Once the player has collected 50 espresso "elements", 
    // the game stops
    if(countOfEspresso > 50) {
    background(0);
    fill(255);
    text("You've had too much coffee. No more for you!", 100, height/2);
    }
}

// Week 10 - Generative landscape notes helped!
function updateAndDisplayEspresso() {
    for (var i = 0; i < numEspresso; i++) {
      espresso[i].draw();
      espresso[i].move();

    var d = dist(espresso[i].x, espresso[i].y, 
      sliderX + sliderW/2, sliderY);
      if (d > 0 & d < 5) {
        countOfEspresso += 1;
      }
  }
}

function mouseDragged() {
  var sliderMax = width - offset - sliderW;
  if(mouseY >= barY & mouseY <= barY+barH){
    sliderX = max(min(mouseX,sliderMax),barX);
  } 
}

function Espresso() {
  this.x = random(0, width);
  this.y = random(0, height);


  this.draw = function() {
    fill(255);
    if (this.y <= height + 2) {
      fill(139, 69, 19);
      ellipse(this.x, this.y, 40, 40);  
    }
    else {
      this.y = -2;
    }
  }

  this.move = function() {
    this.y = this.y + ySpeed;
  } 
}

For my final project, I created a game where the player catches espresso shots (expressed as ellipses) falling from the top of the screen in a cup at the bottom of the canvas. The cup is controlled by a scroller, and the user must drag their mouse in order to move the cup.

The user should move the cup in order to catch the falling espresso “elements” in order to get a (more than healthy, probably way too much!) dose of caffeine. Once the user has caught more than 50 espresso “elements” in their cup, there is a surprise.

In creating my project, I went back and referred to some class notes, notably the lab from Week 3 and the Week 10 deliverables. Having to revisit these ideas helped me solidify my understanding more, and I really appreciated having those resources.

One thing to note – When testing my game, I noticed that the score keeping mechanism is sometimes inconsistent. I went through my code several times and tried many different things to try and fix this bug, but in the end, I failed. 🙁 However, I quite enjoyed working on this project overall, and this project really made me appreciate beautifully made games because it is obvious that there is immense amounts of work that go into them.