我的代码给出了一个黑匣子输出为600*800尺寸,没有其他显示。
我尝试编码基本的pong游戏匿名函数定期调用update((函数,该函数将reset((相应地调用
<canvas id = "gc" width = "640" height = "480"> </canvas>
<script>
userPlankYPosition =40;
computerPlankYPosition = 40;
plankWidth = 10;
plankHeight =100;
ballPositionX=ballPositionY=50;
ballDimension =6;
XVelocity=YVelocity=4;
playerScore=ComputerScore=0;
computerPlankSpeedinY=4;
var canvas,canvasContext;
window.onload=function() {
canvas=document.getElementById('gc');
canvasContext=canvas.getContext('2d');
setInterval(update, 1000/30);
canvas.addEventListener('mousemove',function(e){
userPlankYPosition = e.clientY-plankHeight/2;
});
};
function reset(){
ballPositionX=canvas.width/2;
ballPositionY=canvas.height/2;
XVelocity-=XVelocity;
YVelocity=3;
};
function update(){
canvasContext.fillstyle='black';
canvasContext.fillRect(0,0,canvas.width,canvas.height);
canvasContext.fillstyle='white';
canvasContext.fillRect(0,userPlankYPosition,plankWidth,plankHeight);
canvasContext.fillRect(canvas.width-plankWidth,computerPlankYPosition,plankWidth,plankHeight);
canvasContext.fillRect(ballPositionX-ballDimension/2,ballPositionY-ballDimension/2,ballDimension,ballDimension);
canvasContext.fillText(playerScore,100,100);
canvasContext.fillText(ComputerScore,canvas.width-100,100);
ballPositionX+=XVelocity;
ballPositionY+=YVelocity;
if(ballPositionY<0 && YVelocity <0){
YVelocity-=YVelocity;
}
if(ballPositionY>canvas.height && YVelocity <0){
YVelocity-=YVelocity;
}
if(ballPositionX<0 )
{
if(ballPositionY>userPlankYPosition && ballPositionY<userPlankYPosition+plankHeight){
XVelocity-=XVelocity;
dy=ballPositionY-(userPlankYPosition+plankHeight/2);
YVelocity = dy*0.3;
}
else{
ComputerScore++;
reset();
}
}
if(ballPositionX>canvas.width )
{
if(ballPositionY>computerPlankYPosition && ballPositionY<computerPlankYPosition+plankHeight){
XVelocity-=XVelocity;
dy=ballPositionY-(computerPlankYPosition+plankHeight/2);
YVelocity = dy*0.3;
}
else{
playerScore++;
reset();
}
};
if(computerPlankYPosition+plankHeight/2<ballPositionY){
computerPlankYPosition+=computerPlankSpeedinY;
}
else{
computerPlankYPosition-=computerPlankSpeedinY;
}
// canvasContext.fillstyle='black';
// canvasContext.fillRect(0,0,canvas.width,canvas.height);
// canvasContext.fillstyle='white';
// canvasContext.fillRect(0,userPlankYPosition,plankWidth,plankHeight);
// canvasContext.fillRect(canvas.width-plankWidth,computerPlankYPosition,plankWidth,plankHeight);
// canvasContext.fillRect(ballPositionX-ballDimension/2,ballPositionY-ballDimension/2,ballDimension,ballDimension);
// canvasContext.fillText(playerScore,100,100);
// canvasContext.fillText(ComputerScore,canvas.width-100,100);
};
,输出为:输出
尝试在没有括号的情况下从setInterval调用更新。