Template:Freiburg/pong js

var ctx, canvas_width, canvas_height, board_width, board_heigth, posX, posY, dx, dy, recW, recH, ballSize, img, hitCount, speed; var mouseX, mouseY; var boardPos;

function pong_preload(){ console.log("preloading image"); img = new Image(); img.src = "Freiburg_Dia_pong.png";

img.onload = function () {

  					init();

} }

function init(){ console.log("init pong"); ctx= document.getElementById('pong_canvasObject').getContext('2d'); console.log("canvas initialized"); canvas_width = 675; canvas_height = 400; board_width = 10; board_height = 60; posX = 10; posY = 50; dx = 5; dy = 5; recW = 10; recH = 10; mouseX = 0; boardPos = 0; mouseY =0; hitCount=0; ballSize=10; speed = 5;

document.onmousemove = handleMouseMove; tick(); }

function tick(){ boardPos = mouseY; if(posX>(canvas_width-board_width-ballSize)){ if(posY>boardPos-(board_height/2)-(ballSize/2) & posY<boardPos+(board_height/2)+ballSize/2){ dx +=0.5; dx = -dx; hitCount++; }else{ alert('Congratulations: You lost!\nYour score: '+hitCount+'\n\nWe\'d like to thank all our supporters!\nWe couldn\'t have done it without you :)'); dx = 0; dy = 0; posY = board_height+Math.random()*canvas_height-board_height; posX = board_width; setTimeout(function(){ dx = dy = speed;}, 1000) hitCount=0; draw(); }

}else if(posX<board_width){ dx = -dx; } if(posY>canvas_height- ballSize){ dy = -dy; }else if(posY<ballSize){ dy = -dy; }

posX = posX+dx; posY = posY + dy; setTimeout(function(){tick();}, 20) draw(); }

function draw(){ ctx.stroke(); ctx.clearRect(0, 0, canvas_width, canvas_height); ctx.drawImage(img, canvas_width/4, 0.67*canvas_height/4, canvas_width/2, 0.67*canvas_width/2); ctx.fillStyle="#c1002a"; ctx.fillRect(posX,posY, ballSize, ballSize); ctx.fillRect(0, posY-board_height/2, board_width, board_height); ctx.fillStyle= "#004a99"; ctx.font = "10px Arial"; ctx.fillText("Count: "+ hitCount,canvas_width-50,canvas_height-10);

if(mouseY>canvas_height-board_height/2){ ctx.fillRect(canvas_width-board_width, canvas_height-board_height, board_width, board_height); }else if(mouseY<board_height/2){ ctx.fillRect(canvas_width-board_width, 0, board_width, board_height); }else{ ctx.fillRect(canvas_width-board_width, mouseY-(board_height/2), board_width, board_height); }

}


function handleMouseMove(event) { var canvaswrapper = document.getElementById('canvas_wrap'); var rect = canvaswrapper.getBoundingClientRect();

mouseX = event.pageX-rect.left; mouseY = event.pageY-rect.top; }