实验六 AMPIRE128*64姓名学号显示

#include<reg51.h>
#include<intrins.h>
sbit CS1=P1^1;
sbit CS2=P1^2;
sbit RS=P1^3;
sbit RW=P1^4;
sbit E=P1^5;
sbit RST=P1^0;

int line,colum;

int code english[][32]={/*– 文字: 1 –*/
/*– 楷体_GB231212; 此字体下对应的点阵为:宽x高=8×16 –*/
{0x00,0x10,0x10,0xF8,0x00,0x00,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00},

/*– 文字: 6 –*/
/*– 楷体_GB231212; 此字体下对应的点阵为:宽x高=8×16 –*/
{0x00,0xE0,0x10,0x88,0x88,0x18,0x00,0x00,0x00,0x0F,0x11,0x20,0x20,0x11,0x0E,0x00},

/*– 文字: 0 –*/
/*– 楷体_GB231212; 此字体下对应的点阵为:宽x高=8×16 –*/
{0x00,0xE0,0x10,0x08,0x08,0x10,0xE0,0x00,0x00,0x0F,0x10,0x20,0x20,0x10,0x0F,0x00},

/*– 文字: 6 –*/
/*– 楷体_GB231212; 此字体下对应的点阵为:宽x高=8×16 –*/
{0x00,0xE0,0x10,0x88,0x88,0x18,0x00,0x00,0x00,0x0F,0x11,0x20,0x20,0x11,0x0E,0x00},

/*– 文字: 4 –*/
/*– 楷体_GB231212; 此字体下对应的点阵为:宽x高=8×16 –*/
{0x00,0x00,0xC0,0x20,0x10,0xF8,0x00,0x00,0x00,0x07,0x04,0x24,0x24,0x3F,0x24,0x00},

/*– 文字: 5 –*/
/*– 楷体_GB231212; 此字体下对应的点阵为:宽x高=8×16 –*/
{0x00,0xF8,0x08,0x88,0x88,0x08,0x08,0x00,0x00,0x19,0x21,0x20,0x20,0x11,0x0E,0x00},

/*– 文字: 0 –*/
/*– 楷体_GB231212; 此字体下对应的点阵为:宽x高=8×16 –*/
{0x00,0xE0,0x10,0x08,0x08,0x10,0xE0,0x00,0x00,0x0F,0x10,0x20,0x20,0x10,0x0F,0x00},

/*– 文字: 1 –*/
/*– 楷体_GB231212; 此字体下对应的点阵为:宽x高=8×16 –*/
{0x00,0x10,0x10,0xF8,0x00,0x00,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00},

/*– 文字: 0 –*/
/*– 楷体_GB231212; 此字体下对应的点阵为:宽x高=8×16 –*/
{0x00,0xE0,0x10,0x08,0x08,0x10,0xE0,0x00,0x00,0x0F,0x10,0x20,0x20,0x10,0x0F,0x00},

/*– 文字: 7 –*/
/*– 楷体_GB231212; 此字体下对应的点阵为:宽x高=8×16 –*/
{0x00,0x38,0x08,0x08,0xC8,0x38,0x08,0x00,0x00,0x00,0x00,0x3F,0x00,0x00,0x00,0x00}
};

int code chinese[][32]={/*– 文字: 罗 –*/
/*– 楷体_GB231212; 此字体下对应的点阵为:宽x高=16×16 –*/
{0x00,0x00,0x3E,0x22,0x22,0xBE,0x62,0x22,0x22,0x3E,0x22,0x22,0x3E,0x00,0x00,0x00,
0x80,0x84,0x84,0x42,0x45,0x49,0x31,0x21,0x11,0x09,0x05,0x03,0x00,0x00,0x00,0x00},

/*– 文字: 聪 –*/
/*– 楷体_GB231212; 此字体下对应的点阵为:宽x高=16×16 –*/
{0x02,0xFE,0x92,0x92,0xFE,0x02,0x00,0xF8,0x89,0x8E,0x88,0x8C,0x8B,0xF8,0x00,0x00,
0x10,0x1F,0x08,0x08,0xFF,0x04,0x40,0x38,0x00,0x3C,0x41,0x46,0x60,0x04,0x38,0x00}
};

void delay1ms()
{ int i;
for(i=0;i<124;i++);
}

void delayMs(ms)
{ while(ms–)
delay1ms();
}

void WriteInstruction(int instruction)
{ E=1;
RW=0;
RS=0;
P0=instruction;
E=0;
}

void WriteDat(int dat)
{ E=1;
RW=0;
RS=1;
P0=dat;
E=0;
}

void Setonoff(int onoff)
{ if(onoff==1)
WriteInstruction(0x3f);
else
WriteInstruction(0x3e);
}

void SetLine(int line)
{ line=line&0x07;
line=line|0xb8;
WriteInstruction(line);
}

void SetColum(int colum)
{ colum=colum&0x3f;
colum=colum|0x40;
WriteInstruction(colum);
}

void SetStartline(int startline)
{ startline=startline&0x3f;
startline=startline|0xc0;
WriteInstruction(startline);
}

void SelectScreen(int screen)
{ switch(screen)
{ case 0: CS1=0;delayMs(2);CS2=1;delayMs(2);break;
case 1: CS1=1;delayMs(2);CS2=0;delayMs(2);break;
case 2: CS1=0;delayMs(2);CS2=0;delayMs(2);break;
}
}

void DisplayChinese(int line,int colum,int num)
{ int i;
SetLine(line);
SetColum(colum);
for(i=0;i<16;i++)
{ WriteDat(chinese[num][i]);
}
SetLine(line+1);
SetColum(colum);
for(i=0;i<16;i++)
{ WriteDat(chinese[num][16+i]);
}
}

void DisplayEnglish(int line,int colum,int num)
{ int i;
SetLine(line);
SetColum(colum);
for(i=0;i<8;i++)
{ WriteDat(english[num][i]);
}
SetLine(line+1);
SetColum(colum);
for(i=0;i<8;i++)
{ WriteDat(english[num][8+i]);
}
}

void ClearScreen(int screen)
{ int i,j;
SelectScreen(screen);
for(i=0;i<8;i++)
{ SetLine(i);
SetColum(0);
for(j=0;j<64;j++)
WriteDat(0);
}
}

void LcdInit()
{ Setonoff(0);
ClearScreen(2);
SetLine(0);
SetColum(0);
SetStartline(0);
Setonoff(1);
}

void main()
{

int i;
LcdInit();
while(1)
{ line=3;
colum=0;
Setonoff(1);

for(i=0;i<10;i++)
{ if(i<8)
{ SelectScreen(0);
DisplayEnglish(line,8*i,i);
}
else
{ SelectScreen(1);
DisplayEnglish(line,8*i,i);
}
}
for(i=0;i<2;i++)
{ SelectScreen(1);
DisplayChinese(line,16*i+24,i);
}
}
}

实验五 8*8数码管名字滚动显示

#include<reg51.h>
void delay()
{
int i;
for(i=0;i<500;i++);
}
void delay1()
{
int a;
for(a=0;a<700;a++);
}

void main()
{
int j,k;
int code a[]={0x0 ,0x4 ,0x7f ,0xfe ,0x44 ,0x44 ,0x44 ,0x44 ,0x44 ,0x44 ,0x7f ,0xfc ,0x42 ,0x4 ,0x2 ,0x0 ,0x7 ,0xf0 ,0x8 ,0x10 ,0x14 ,0x20 ,0x62 ,0xc0 ,0x1 ,0x0 ,0x6 ,0x0 ,0x18 ,0x0 ,0xe0 ,0x0};
int code b[]={0x5 ,0x4 ,0xfe ,0xcc ,0x24 ,0x50 ,0x24 ,0x4 ,0x3d ,0xfe ,0x25 ,0x4 ,0x25 ,0x4 ,0x25 ,0x4 ,0x3d ,0xfc ,0x25 ,0x44 ,0x24 ,0x20 ,0x24 ,0xa4 ,0xfd ,0x8a ,0x6 ,0x8a ,0x4 ,0x78 ,0x4 ,0x0};
while(1)
{
for(j=0;j<16;j++)
{
P2=~a[2*j];
P0=~a[2*j+1];
P1=j;
delay();
}
for(j=0,k=1;j<15,k<16;j++,k++)
{
for(j=0;j<16;j++)
{
P2=~((a[2*j])<<k);
P0=~((a[2*j+1])<<k);
P1=j;
delay1();
}
}
for(j=0;j<16;j++)
{
P2=~b[2*j];
P0=~b[2*j+1];
P1=j;
delay();
}
for(j=0,k=1;j<15,k<16;j++,k++)
{
for(j=0;j<16;j++)
{
P2=~((b[2*j])<<k);
P0=~((b[2*j+1])<<k);
P1=j;
delay1();
}
}
}
}

实验四 电子琴

/*自动播放的代码
#include<reg51.h>
sbit beep=P1^0;
unsigned char frql,frqh;

void timer0_isr() interrupt 1
{ TH0=frqh;
TL0=frql;
beep=~beep;
}

void delayMS(int ms)
{ int j;
while(ms–)
for(j=0;j<120;j++);
}

main()
{ int i;
int code frq[]={0,523,587,659,698,784,880,988};
int code song[]={5,1,1,1,3,2,1,2,3,1,1,3,5,6,6,5,3,3,1,2,1,2,3,1,6,6,5,1,6,5,3,3,1,2,1,2,6,5,3,3,5,6,1,5,3,3,1,2,1,2,3,1,6,6,5,1};
int code du[]={1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,2,2,1,2};
int code a[]={200,300,100,200,200,300,100,200,200,300,100,200,200,100,200,300,100,200,200,300,100,200,200,300,100,200,200,100,200,200,100,200,200,200,100,200,200,200,100,200,200,100,100,300,100,200,200,300,100,200,200,300,100,200,200,100,100,200,100};

EA=1;
ET0=1;
TMOD=0x01;
while(1)
{
for(i=0;i<25;i++)
{
frqh=(65535-500000/(frq[song[i]]*du[i]/2))/256;
frql=(65535-500000/(frq[song[i]]*du[i]/2))%256;
TR0=1;
delayMS(a[i]*1.5);
TR0=0;
delayMS(5);
}
TR0=0;
delayMS(1000);
}
}
*/

#include<reg51.h>
sbit beep=P1^0;
sbit SW1=P2^0;
sbit SW2=P2^1;
int h,l;

/*void delay()
{ int i,j;
for(i=0;i<120;i++)
for(j=0;j<120;j++)
}*/

void timer0_isr() interrupt 1
{ TH0=h;
TL0=l;
beep=~beep;
}

main()
{
EA=1;
ET0=1;
TMOD=0x01;
while(1)
{
P1=0xff;

switch(P0)
{
case 0xfe:
h=(65535-500000/2/523)/256;
l=(65535-500000/2/523)%256;
TR0=1;
break;
case 0xfd:
h=(65535-500000/2/587)/256;
l=(65535-500000/2/587)%256;
TR0=1;
break;
case 0xfb:
h=(65535-500000/2/659)/256;
l=(65535-500000/2/659)%256;
TR0=1;
break;
case 0xf7:
h=(65535-500000/2/698)/256;
l=(65535-500000/2/698)%256;
TR0=1;
break;
case 0xef:
h=(65535-500000/2/784)/256;
l=(65535-500000/2/784)%256;
TR0=1;
break;
case 0xdf:
h=(65535-500000/2/880)/256;
l=(65535-500000/2/880)%256;
TR0=1;
break;
case 0xbf:
h=(65535-500000/2/988)/256;
l=(65535-500000/2/988)%256;
TR0=1;
break;
default:
TR0=0;
break;
}

switch(P2)
{
case 0xfe:
h=(65535-500000/523)/256;
l=(65535-500000/523)%256;
TR0=1;
break;
case 0xfd:
h=(65535-500000/587)/256;
l=(65535-500000/587)%256;
TR0=1;
break;
case 0xfb:
h=(65535-500000/659)/256;
l=(65535-500000/659)%256;
TR0=1;
break;
case 0xf7:
h=(65535-500000/698)/256;
l=(65535-500000/698)%256;
TR0=1;
break;
case 0xef:
h=(65535-500000/784)/256;
l=(65535-500000/784)%256;
TR0=1;
break;
case 0xdf:
h=(65535-500000/880)/256;
l=(65535-500000/880)%256;
TR0=1;
break;
case 0xbf:
h=(65535-500000/988)/256;
l=(65535-500000/988)%256;
TR0=1;
break;
default:
TR0=0;
break;
}

switch(P3)
{
case 0xfe:
h=(65535-500000*2/523)/256;
l=(65535-500000*2/523)%256;
TR0=1;
break;
case 0xfd:
h=(65535-500000*2/587)/256;
l=(65535-500000*2/587)%256;
TR0=1;
break;
case 0xfb:
h=(65535-500000*2/659)/256;
l=(65535-500000*2/659)%256;
TR0=1;
break;
case 0xf7:
h=(65535-500000*2/698)/256;
l=(65535-500000*2/698)%256;
TR0=1;
break;
case 0xef:
h=(65535-500000*2/784)/256;
l=(65535-500000*2/784)%256;
TR0=1;
break;
case 0xdf:
h=(65535-500000*2/880)/256;
l=(65535-500000*2/880)%256;
TR0=1;
break;
case 0xbf:
h=(65535-500000*2/988)/256;
l=(65535-500000*2/988)%256;
TR0=1;
break;
default:
TR0=0;
break;
}
}
}

html游戏七:五子棋

// JavaScript Document

//借鉴算法
var over = false;
var me = true; //定义玩家自己
var _nowi = 0,
_nowj = 0; //记录自己下棋的坐标
var _compi = 0,
_compj = 0; //记录计算机当前下棋的坐标
var _myWin = [],
_compWin = []; //记录我,计算机赢的情况
var backAble = false,
returnAble = false;
var resultTxt = document.getElementById(“result-wrap”);
var chressBord = []; //棋盘
for (var i = 0; i < 15; i++) {
chressBord[i] = [];
for (var j = 0; j < 15; j++) {
chressBord[i][j] = 0;
}
}
//赢法的统计数组
var myWin = [];
var computerWin = [];
//赢法数组
var wins = [];
for (var i = 0; i < 15; i++) {
wins[i] = [];
for (var j = 0; j < 15; j++) {
wins[i][j] = [];
}
}
var count = 0; //赢法总数
//横线赢法
for (var i = 0; i < 15; i++) {
for (var j = 0; j < 11; j++) {
for (var k = 0; k < 5; k++) {
wins[i][j + k][count] = true;
}
count++;
}
}
//竖线赢法
for (var i = 0; i < 15; i++) {
for (var j = 0; j < 11; j++) {
for (var k = 0; k < 5; k++) {
wins[j + k][i][count] = true;
}
count++;
}
}
//正斜线赢法
for (var i = 0; i < 11; i++) {
for (var j = 0; j < 11; j++) {
for (var k = 0; k < 5; k++) {
wins[i + k][j + k][count] = true;
}
count++;
}
}
//反斜线赢法
for (var i = 0; i < 11; i++) {
for (var j = 14; j > 3; j–) {
for (var k = 0; k < 5; k++) {
wins[i + k][j – k][count] = true;
}
count++;
}
}
// debugger;
for (var i = 0; i < count; i++) {
myWin[i] = 0;
_myWin[i] = 0;
computerWin[i] = 0;
_compWin[i] = 0;
}
var chess = document.getElementById(“chess”);
var context = chess.getContext(‘2d’);
context.strokeStyle = ‘#bfbfbf’; //边框颜色
var backbtn = document.getElementById(“goback”);
var returnbtn = document.getElementById(“return”);
window.onload = function () {
drawChessBoard(); // 画棋盘
}
document.getElementById(“restart”).onclick = function () {
window.location.reload();
}
// 我,下棋
chess.onclick = function (e) {
if (over) {
return;
}
if (!me) {
return;
}
// 悔棋功能可用
backbtn.className = backbtn.className.replace(new RegExp(“(\\s|^)unable(\\s|$)”), ” “);
var x = e.offsetX;
var y = e.offsetY;
var i = Math.floor(x / 30);
var j = Math.floor(y / 30);
_nowi = i;
_nowj = j;
if (chressBord[i][j] == 0) {
oneStep(i, j, me);
chressBord[i][j] = 1; //我,已占位置

for (var k = 0; k < count; k++) { // 将可能赢的情况都加1
if (wins[i][j][k]) {
// debugger;
myWin[k]++;
_compWin[k] = computerWin[k];
computerWin[k] = 6; //这个位置对方不可能赢了
if (myWin[k] == 5) {
// window.alert(‘你赢了’);
resultTxt.innerHTML = ‘恭喜,你赢了!’;
over = true;
}
}
}
if (!over) {
me = !me;
computerAI();
}
}
}
// 悔棋
backbtn.onclick = function (e) {
if (!backAble) {
return;
}
over = false;
me = true;
// resultTxt.innerHTML = ‘o(╯□╰)o,悔棋中’;
// 撤销悔棋功能可用
returnbtn.className = returnbtn.className.replace(new RegExp(“(\\s|^)unable(\\s|$)”), ” “);
// 我,悔
chressBord[_nowi][_nowj] = 0; //我,已占位置 还原
minusStep(_nowi, _nowj); //销毁棋子

for (var k = 0; k < count; k++) { // 将可能赢的情况都减1
if (wins[_nowi][_nowj][k]) {
myWin[k]–;
computerWin[k] = _compWin[k]; //这个位置对方可能赢
}
}
// 计算机相应的悔棋
chressBord[_compi][_compj] = 0; //计算机,已占位置 还原
minusStep(_compi, _compj); //销毁棋子

for (var k = 0; k < count; k++) { // 将可能赢的情况都减1
if (wins[_compi][_compj][k]) {
computerWin[k]–;
myWin[k] = _myWin[i]; //这个位置对方可能赢
}
}
resultTxt.innerHTML = ‘–益智五子棋–‘;
returnAble = true;
backAble = false;
}
// 撤销悔棋
returnbtn.onclick = function (e) {
if (!returnAble) {
return;
}
// 我,撤销悔棋
chressBord[_nowi][_nowj] = 1; //我,已占位置
oneStep(_nowi, _nowj, me);
for (var k = 0; k < count; k++) {
if (wins[_nowi][_nowj][k]) {
myWin[k]++;
_compWin[k] = computerWin[k];
computerWin[k] = 6; //这个位置对方不可能赢
}
if (myWin[k] == 5) {
resultTxt.innerHTML = ‘恭喜,你赢了!’;
over = true;
}
}
// 计算机撤销相应的悔棋
chressBord[_compi][_compj] = 2; //计算机,已占位置
oneStep(_compi, _compj, false);
for (var k = 0; k < count; k++) { // 将可能赢的情况都减1
if (wins[_compi][_compj][k]) {
computerWin[k]++;
_myWin[k] = myWin[k];
myWin[k] = 6; //这个位置对方不可能赢
}
if (computerWin[k] == 5) {
resultTxt.innerHTML = ‘o(╯□╰)o,计算机赢了,继续加油哦!’;
over = true;
}
}
returnbtn.className += ” + ‘unable’;
returnAble = false;
backAble = true;
}

// 计算机下棋
var computerAI = function () {
var myScore = [];
var computerScore = [];
var max = 0;
var u = 0,
v = 0;
for (var i = 0; i < 15; i++) {
myScore[i] = [];
computerScore[i] = [];
for (var j = 0; j < 15; j++) {
myScore[i][j] = 0;
computerScore[i][j] = 0;
}
}
for (var i = 0; i < 15; i++) {
for (var j = 0; j < 15; j++) {
if (chressBord[i][j] == 0) {
for (var k = 0; k < count; k++) {
if (wins[i][j][k]) {
if (myWin[k] == 1) {
myScore[i][j] += 200;
} else if (myWin[k] == 2) {
myScore[i][j] += 400;
} else if (myWin[k] == 3) {
myScore[i][j] += 2000;
} else if (myWin[k] == 4) {
myScore[i][j] += 10000;
}

if (computerWin[k] == 1) {
computerScore[i][j] += 220;
} else if (computerWin[k] == 2) {
computerScore[i][j] += 420;
} else if (computerWin[k] == 3) {
computerScore[i][j] += 2100;
} else if (computerWin[k] == 4) {
computerScore[i][j] += 20000;
}
}
}

if (myScore[i][j] > max) {
max = myScore[i][j];
u = i;
v = j;
} else if (myScore[i][j] == max) {
if (computerScore[i][j] > computerScore[u][v]) {
u = i;
v = j;
}
}

if (computerScore[i][j] > max) {
max = computerScore[i][j];
u = i;
v = j;
} else if (computerScore[i][j] == max) {
if (myScore[i][j] > myScore[u][v]) {
u = i;
v = j;
}
}
}
}
}
_compi = u;
_compj = v;
oneStep(u, v, false);
chressBord[u][v] = 2; //计算机占据位置
for (var k = 0; k < count; k++) {
if (wins[u][v][k]) {
computerWin[k]++;
_myWin[k] = myWin[k];
myWin[k] = 6; //这个位置对方不可能赢了
if (computerWin[k] == 5) {
resultTxt.innerHTML = ‘o(╯□╰)o,计算机赢了,继续加油哦!’;
over = true;
}
}
}
if (!over) {
me = !me;
}
backAble = true;
returnAble = false;
var hasClass = new RegExp(‘unable’).test(” +
returnbtn.className + ”);
if (hasClass) {
returnbtn.className += ” + ‘unable’;
}
}
//绘画棋盘
var drawChessBoard = function () {
for (var i = 0; i < 15; i++) {
context.moveTo(15 + i * 30, 15);
context.lineTo(15 + i * 30, 435);
context.stroke();
context.moveTo(15, 15 + i * 30);
context.lineTo(435, 15 + i * 30);
context.stroke();
}
}
//画棋子
var oneStep = function (i, j, me) {
context.beginPath();
context.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * Math.PI); // 画圆
context.closePath();
//渐变
var gradient = context.createRadialGradient(15 + i * 30 +
2, 15 + j * 30 – 2, 13, 15 + i * 30 + 2, 15 + j * 30 –
2, 0);
if (me) {
gradient.addColorStop(0, ‘#0a0a0a’);
gradient.addColorStop(1, ‘#636766’);
} else {
gradient.addColorStop(0, ‘#d1d1d1’);
gradient.addColorStop(1, ‘#f9f9f9’)
}
context.fillStyle = gradient;
context.fill();
}
//销毁棋子
var minusStep = function (i, j) {
//擦除该圆
context.clearRect((i) * 30, (j) * 30, 30, 30);
// 重画该圆周围的格子
context.beginPath();
context.moveTo(15 + i * 30, j * 30);
context.lineTo(15 + i * 30, j * 30 + 30);
context.moveTo(i * 30, j * 30 + 15);
context.lineTo((i + 1) * 30, j * 30 + 15);
context.stroke();
}

html游戏六:五彩连珠

// JavaScript Document
var game = {
canvas: document.getElementById(“canvas”),
ctx: document.getElementById(“canvas”).getContext(“2d”),
cellCount: 9,       //9*9九宫格
cellWidth: 30,         //方格大小
lineCount: 5,
mode: 7,
actions: {},
play: function (name, action, interval) {
var me = this;
this.actions[name] = setInterval(function () {
action();
me.draw();
}, interval || 50);
},
stop: function (name) {
clearInterval(this.actions[name]);
this.draw();
},
colors: [“red”, “#039518”, “#ff00dc”, “#ff6a00”, “gray”, “#0094ff”, “#d2ce00”],
start: function () {
this.map.init();
this.ready.init();
this.draw();
this.canvas.onclick = this.onclick;
},
over: function () {
alert(“GAME OVER”);
this.onclick = function () {
return false;
};
},
draw: function () {
this.ctx.clearRect(0, 0, 400, 600);
this.ctx.save();
this.map.draw();
this.ready.draw();
this.score.draw();
this.ctx.restore();
},
clicked: null,
isMoving: function () {
return this.ready.isMoving || this.map.isMoving;
},
onclick: function (e) {
if (game.isMoving()) {
return;
}
var px = (e.offsetX || (e.clientX – game.canvas.offsetLeft)) – game.map.startX;
var py = (e.offsetY || (e.clientY – game.canvas.offsetTop)) – game.map.startY;
if (px < 0 || py < 0 || px > game.map.width || py > game.map.height) {
return;
}
var x = parseInt(px / game.cellWidth);
var y = parseInt(py / game.cellWidth);
var clicked = game.clicked;
var bubble = game.map.getBubble(x, y);
if (bubble.color) {
if (clicked) {
//同一个泡不做反映
if (clicked.x == x && clicked.y == y) {
return;
}
clicked.stop();
}
clicked = game.clicked = bubble;
bubble.play();
} else {
if (clicked) {
clicked.stop();
//移动clicked
game.map.move(clicked, bubble);
}
}
//console.log(“x:” + x + ” y:” + y);
},
getRandom: function (max) {
return parseInt(Math.random() * 1000000 % (max));
},
};
game.score = {
basic: 0,
operate: 0,
star1: 0,
star2: 0,
boom: 0,
draw: function () {
var startX = game.cellWidth * 10 + game.map.startX;
var startY = game.map.startY;
var ctx = game.ctx;
ctx.save();
ctx.translate(startX, startY);
ctx.clearRect(0, 0, 150, 400);
ctx.strokeStyle = “#456”;
//ctx.strokeRect(0, 0, 150, 200);
ctx.font = “24px 微软雅黑”;
ctx.fillStyle = “#fefefe”;
ctx.fillText(“得分:” + (this.basic * 5 + this.star1 * 8 + this.star2 * 10 + this.boom * 20), 0, 30);
ctx.stroke();
ctx.restore();
},
addScore: function (length) {
switch (length) {
case 5:
this.basic++;
break;
case 6:
this.star1++;
break;
case 7:
this.star2++;
break;
default:
this.boom++;
break;
}
this.draw();
},
};
game.ready = {
startX: 41.5,
startY: 21.5,
width: game.cellWidth * 3,
height: game.cellWidth,
bubbles: [],
init: function () {
this.genrate();
var me = this;
me.flyin();
},
genrate: function () {
for (var i = 0; i < 3; i++) {
var color = game.colors[game.getRandom(game.mode)];
this.bubbles.push(new Bubble(i, 0, color));
}
//console.log(this.bubbles);
},
draw: function () {
var ctx = game.ctx;
ctx.save();
ctx.translate(this.startX, this.startY);
ctx.beginPath();
ctx.strokeStyle = “#555”;
ctx.strokeRect(0, 0, this.width, this.height);
ctx.stroke();
//绘制准备的泡
this.bubbles.forEach(function (bubble) {
bubble.draw();
});

ctx.restore();
},
isMoving: false,
flyin: function () {
var emptys = game.map.getEmptyBubbles();
if (emptys.length < 3) {
//游戏结束
game.over();
return;
}
var me = this;
var status = [0, 0, 0];
var times = 1;
game.play(“flyin”, function () {
if (status[0] && status[1] && status[2]) {
game.stop(“flyin”);
me.isMoving = false;
status = [0, 0, 0];
me.bubbles = [];
me.genrate();
return;
}
me.isMoving = true;
for (var i = 0; i < me.bubbles.length; i++) {
if (status[i]) {
continue;
}
var target = emptys[i];
var x2 = target.px + game.map.startX – me.startX;
var y2 = target.py + game.map.startY – me.startY;
var current = me.bubbles[i];
var step = Math.abs(x2 – current.px) / 10 || Math.abs(y2 – current.y) / 10;
if (current.px < x2) {
current.py = ((y2 – current.py) / (x2 – current.px)) * step + current.py;
current.px += step;
if (current.px > x2) {
current.px = x2;
}
} else if (current.px > x2) {
current.py = ((y2 – current.py) / (current.px – x2)) * step + current.py;
current.px -= step;
if (current.px < x2) {
current.px = x2;
}
} else {
current.py += step;
}
if (current.py > y2) {
current.py = y2;
}
if (parseInt(current.px + 0.1) == x2 && parseInt(current.py + 0.1) == y2) {
status[i] = 1;
current.x = target.x;
current.y = target.y;
game.map.addBubble(current);
game.map.clearLine(current.x, current.y, current.color, false);
}
}
}, 10);

}
};
game.map = {
startX: 40.5, //棋盘X坐标
startY: 60.5, //棋盘Y坐标
width: game.cellCount * game.cellWidth,
height: game.cellCount * game.cellWidth,
bubbles: [],
init: function () {
for (var i = 0; i < game.cellCount; i++) {
var row = [];
for (var j = 0; j < game.cellCount; j++) {
row.push(new Bubble(j, i, null));
}
this.bubbles.push(row);
}
},
clearLine: function (x1, y1, color, isClick) {
if (this.isEmpty(x1, y1)) {
if (isClick) game.ready.flyin();
return;
};
//给定一个坐标,看是否有满足的line可以被消除
//4根线 一 | / \
//横线
var current = this.getBubble(x1, y1);
if (!current.color) {
console.log(current);
}
var arr1, arr2, arr3, arr4;
arr1 = this.bubbles[y1];
arr2 = [];
for (var y = 0; y < game.cellCount; y++)
arr2.push(this.getBubble(x1, y));
arr3 = [current];
arr4 = [current];
for (var i = 1; i < game.cellCount; i++) {
if (x1 – i >= 0 && y1 – i >= 0)
arr3.unshift(this.getBubble(x1 – i, y1 – i));
if (x1 + i < game.cellCount && y1 + i < game.cellCount)
arr3.push(this.getBubble(x1 + i, y1 + i));

if (x1 – i >= 0 && y1 + i < game.cellCount)
arr4.push(this.getBubble(x1 – i, y1 + i));
if (x1 + i < game.cellCount && y1 – i >= 0)
arr4.unshift(this.getBubble(x1 + i, y1 – i));
}
var line1 = getLine(arr1);
var line2 = getLine(arr2);
var line3 = getLine(arr3);
var line4 = getLine(arr4);
var line = line1.concat(line2).concat(line3).concat(line4);
if (line.length < 5) {
if (isClick) game.ready.flyin();
return;
} else {
var me = this;
var i = 0;
game.play(“clearline”, function () {
if (i == line.length) {
game.score.addScore(line.length);
game.stop(“clearline”);
me.isMoving = false;
//game.ready.flyin();
return;
}
me.isMoving = true;
var p = line[i];
me.setBubble(p.x, p.y, null);
i++;
}, 100);
}

function getLine(bubbles) {

var line = [];
for (var i = 0; i < bubbles.length; i++) {
var b = bubbles[i];
if (b.color == color) {
line.push({
“x”: b.x,
“y”: b.y
});
} else {
if (line.length < 5)
line = [];
else
return line;
}
}
if (line.length < 5)
return [];
return line;
}
},
draw: function () {
var ctx = game.ctx;
ctx.save();
ctx.translate(this.startX, this.startY);
ctx.beginPath();
for (var i = 0; i <= game.cellCount; i++) {
var p1 = i * game.cellWidth;;
ctx.moveTo(p1, 0);
ctx.lineTo(p1, this.height);

var p2 = i * game.cellWidth;
ctx.moveTo(0, p2);
ctx.lineTo(this.width, p2);
}
ctx.strokeStyle = “#555”;
ctx.stroke();
//绘制子元素(所有在棋盘上的泡)
this.bubbles.forEach(function (row) {
row.forEach(function (bubble) {
bubble.draw();
});
});
ctx.restore();
},
isMoving: false,
move: function (bubble, target) {
var path = this.search(bubble.x, bubble.y, target.x, target.y);
if (!path) {
//显示不能移动s
//alert(“过不去”);
return;
}
//map开始播放当前泡的移动效果
//两种实现方式,1、map按路径染色,最后达到目的地 2、map生成一个临时的bubble负责展示,到目的地后移除
//console.log(path);
var me = this;
var name = “move_” + bubble.x + “_” + bubble.y;
var i = path.length – 1;
var color = bubble.color;
game.play(name, function () {
if (i < 0) {
game.stop(name);
game.clicked = null;
me.isMoving = false;
me.clearLine(target.x, target.y, color, true);
return;
}
me.isMoving = true;
path.forEach(function (cell) {
me.setBubble(cell.x, cell.y, null);
});
var currentCell = path[i];
me.setBubble(currentCell.x, currentCell.y, color);
i–;
}, 50);
},
search: function (x1, y1, x2, y2) {
var history = [];
var goalCell = null;
var me = this;
getCell(x1, y1, null);
if (goalCell) {
var path = [];

var cell = goalCell;
while (cell) {
path.push({
“x”: cell.x,
“y”: cell.y
});
cell = cell.parent;
}
return path;
}
return null;

function getCell(x, y, parent) {
if (x >= me.bubbles.length || y >= me.bubbles.length)
return;
if (x != x1 && y != y2 && !me.isEmpty(x, y))
return;

for (var i = 0; i < history.length; i++) {
if (history[i].x == x && history[i].y == y)
return;
}
var cell = {
“x”: x,
“y”: y,
child: [],
“parent”: parent
};
history.push(cell);

if (cell.x == x2 && cell.y == y2) {
goalCell = cell;
return cell;
}
var child = [];
var left, top, right, buttom;
//最短路径的粗略判断就是首选目标位置的大致方向
if (x – 1 >= 0 && me.isEmpty(x – 1, y))
child.push({
“x”: x – 1,
“y”: y
});
if (x + 1 < me.bubbles.length && me.isEmpty(x + 1, y))
child.push({
“x”: x + 1,
“y”: y
});
if (y + 1 < me.bubbles.length && me.isEmpty(x, y + 1))
child.push({
“x”: x,
“y”: y + 1
});
if (y – 1 >= 0 && me.isEmpty(x, y – 1))
child.push({
“x”: x,
“y”: y – 1
});
var distance = [];
for (var i = 0; i < child.length; i++) {
var c = child[i];
if (c) {
distance.push({
“i”: i,
“d”: Math.abs(x2 – c.x) + Math.abs(y2 – c.y)
});
} else {
distance.push({
“i”: i,
“d”: -1
});
}
};
distance.sort(function (a, b) {
return a.d – b.d
});
for (var i = 0; i < child.length; i++) {
var d = distance[i];
var c = child[d.i];
if (c) cell.child.push(getCell(c.x, c.y, cell));
}
return cell;
}
},
getEmptyBubbles: function () {
var empties = [];
this.bubbles.forEach(function (row) {
row.forEach(function (bubble) {
if (!bubble.color) {
empties.push(new Bubble(bubble.x, bubble.y));
}
});
});
if (empties.length <= 3) {
return [];
}
var result = [];
var useds = [];
for (var i = 0; i < empties.length; i++) {
if (result.length == 3) {
break;
}
var isUsed = false;
var ra = game.getRandom(empties.length);
for (var m = 0; m < useds.length; m++) {
isUsed = ra === useds[m];
if (isUsed) break;
}
if (!isUsed) {
result.push(empties[ra]);
useds.push(ra);
}
}
//console.log(useds);
return result;
},
addBubble: function (bubble) {
var thisBubble = this.getBubble(bubble.x, bubble.y);
thisBubble.color = bubble.color;
},
setBubble: function (x, y, color) {
this.getBubble(x, y).color = color;
},
getBubble: function (x, y) {
if (x < 0 || y < 0 || x > game.cellCount || y > game.cellCount) return null;
return this.bubbles[y][x];
},
isEmpty: function (x, y) {
var bubble = this.getBubble(x, y);
return !bubble.color;
},
};
var Cell = function (x, y) {
this.x = x;
this.y = y;
}
var Bubble = function (x, y, color) {
this.x = x;
this.y = y;
this.px = game.cellWidth * (this.x + 1) – game.cellWidth / 2;
this.py = game.cellWidth * (this.y + 1) – game.cellWidth / 2;
this.color = color;
this.light = 10;
};
Bubble.prototype.draw = function () {
if (!this.color) {
return;
}
var ctx = game.ctx;
ctx.beginPath();
//console.log(“x:” + px + “y:” + py);
var gradient = ctx.createRadialGradient(this.px – 5, this.py – 5, 0, this.px, this.py, this.light);
gradient.addColorStop(0, “white”);
gradient.addColorStop(1, this.color);
ctx.arc(this.px, this.py, 11, 0, Math.PI * 2);
ctx.strokeStyle = this.color;
ctx.fillStyle = gradient;
ctx.fill();
ctx.stroke();
};
Bubble.prototype.play = function () {
var me = this;
var isUp = true;
game.play(“light_” + this.x + “_” + this.y, function () {
if (isUp) {
me.light += 3;
}

if (!isUp) {
me.light -= 3;
}
if (me.light >= 30) {
isUp = false;
}
if (me.light <= 10) {
isUp = true;
}
}, 50);
};
Bubble.prototype.stop = function () {
//this.light = 10;
var me = this;
game.stop(“light_” + this.x + “_” + this.y);
game.play(“restore_” + this.x + “_” + this.y, function () {
if (me.light > 10) {
me.light–;
} else {
me.light = 10;
game.stop(“restore_” + me.x + “_” + me.y);
}
}, 50);
};
game.start();

html游戏五:别踩白块

// JavaScript Document
//得当前样式
function getStyle(obj, arrt) {
//兼容IE浏览器
return obj.currentStyle ? obj.currentStyle[arrt] : getComputedStyle(obj, null)[arrt];
}

var main = document.getElementById(‘main’);
var go = document.getElementById(‘go’);
var count = document.getElementById(‘count’);
var cols = [‘#1AAB8A’, ‘#E15650’, ‘#121B39’, ‘#80A84E’];

//动态创建div
function cDiv(classname) {
//创建div
var oDiv = document.createElement(‘div’);
//随机数
var index = Math.floor(Math.random() * 4);
//行 添加相应的class类
oDiv.className = classname;
//创建行之后再动态创建4个小div并添加到行里面
for (var j = 0; j < 4; j++) {
var iDiv = document.createElement(‘div’);
oDiv.appendChild(iDiv);
}
//然后把行添加到main里面
//判断需要添加的位置
if (main.children.length == 0) {
main.appendChild(oDiv);
} else {
main.insertBefore(oDiv, main.children[0]);
}
//随机给行里面的某一个div添加背景色
oDiv.children[index].style.backgroundColor = cols[index];
//标记颜色盒子
oDiv.children[index].className = “i”;
}

//移动div
function move(obj) {
//关闭上一个定时器
clearInterval(obj.timer);
//默认速度与计分
var speed = 5,
num = 0;
//定时器管理与开启定时器
obj.timer = setInterval(function () {
//速度
var step = parseInt(getStyle(obj, ‘top’)) + speed;
//移动盒子
obj.style.top = step + ‘px’;
//判断并创建新的盒子
if (parseInt(getStyle(obj, ‘top’)) >= 0) {
cDiv(‘row’);
obj.style.top = -150 + ‘px’;
}
//删除边界外的盒子
if (obj.children.length == 6) {
//删除前,如果有盒子没有点击则结束游戏
for (var i = 0; i < 4; i++) {
if (obj.children[obj.children.length – 1].children[i].className == ‘i’) {
//游戏结束
obj.style.top = ‘-150px’;
count.innerHTML = ‘游戏结束,最高得分: ‘ + num;
//关闭定时器
clearInterval(obj.timer);
//显示开始游戏
go.children[0].innerHTML = ‘重新开始’;
go.style.display = “block”;
}
}
obj.removeChild(obj.children[obj.children.length – 1]);
}

//点击与计分
obj.onmousedown = function (event) {
//点击的不是白盒子
// 兼容IE浏览器
event = event || window.event;
if ((event.target ? event.target : event.srcElement).className == ‘i’) {
//点击后的盒子颜色
(event.target ? event.target : event.srcElement).style.backgroundColor = “#bbb”;
//清除盒子标记
(event.target ? event.target : event.srcElement).className = ”;
//计分
num++;
//显示得分
count.innerHTML = ‘当前得分: ‘ + num;
bgm.play();
} else {
//游戏结束
obj.style.top = 0;
count.innerHTML = ‘游戏结束,最高得分: ‘ + num;
//关闭定时器
clearInterval(obj.timer);
//显示开始游戏
go.children[0].innerHTML = ‘重新开始’;
go.style.display = “block”;
}
//盒子加速
if (num % 10 == 0) {
speed++;
}
}
//松开触发停止
obj.onmouseup = function (event) {
bgm.pause();
}
}, 20)
}

//开始游戏
go.children[0].onclick = function () {
//开始前判断main里面是否有盒子,有则全部删除
if (main.children.length) {
//暴力清楚main里面所有盒子
main.innerHTML = ”;
}
//清空计分
count.innerHTML = ‘游戏开始’;
//隐藏开始盒子
this.parentNode.style.display = “none”;
//调用定时器
move(main);
}

html游戏四:贪吃蛇

// JavaScript Document

//const定义的变量不会被修改
const WIDTH = 1000;     //定义地图长度
const HEIGHT = 700;       //定义地图宽度
const SNACK_WIDTH = 20;    //移动时间间隔
const SNACK_HEIGHT = 20;
const TIME_MOVE = 300;    //食物刷新时间
const TIME_FOOD = 5000;    //食物总量
const TOTAL_FOOD = 200;    //石头刷新时间
const TIME_STONE = 8000;    //石头总量
const TOTAL_STONE = 300;

var switchStatus = 0;
var changeMove = “right”;
var currentMove = “right”;    //所有被用的位置
var points = new Array();
var snacks = new Array();
var foods = new Array();
var stones = new Array();
var moveing = false;
var timeMoveId, timeFoodId, timeStoneId;
window.onload = function () {
createGround();
};

//判断按的哪个键
function keyDown(event) {
if (event.keyCode == “87”) {          //按下W键

changeMove = “up”;
} else if (event.keyCode == “68”) {          //按下D键

changeMove = “right”;
} else if (event.keyCode == “83”) {          //按下S键

changeMove = “down”;
} else if (event.keyCode == “65”) {          //按下A键

changeMove = “left”;
}
}

function handlePoints(x, y, type) {
if (0 == type) {
points.push(x + y * WIDTH);
} else {
var index = points.indexOf(x + y * WIDTH);
if (index != -1) {
points.splice(index, 1);
}
}
}

function snack(x, y) {      //snack()方法用于得到蛇的位置
this.x = x;
this.y = y;
}

function food(x, y) {                //food()方法用于得到食物的位置
this.x = x;
this.y = y;
}

function stone(x, y) {            //stone()方法用于得到石头的位置
this.x = x;
this.y = y;
}

function clickSwitch() {            //游戏的开始和暂停按钮
if (switchStatus == 0 || switchStatus == 2) {
document.getElementById(“switch”).value = “暂停”;
if (switchStatus == 0) {

play();          //开始
}
switchStatus = 1;
} else if (switchStatus == 1) {
document.getElementById(“switch”).value = “继续”;
switchStatus = 2;
}
}

//碰撞判定并操作
function judge(x, y) {       // 判断是否撞上边界
if (x < 0 || x >= WIDTH || y < 0 || y >= HEIGHT) {
end();
return;
}
var i;       //判断是否撞上自己
for (i = 1; i < snacks.length; i++) {
if (snacks[0].x == snacks[i].x && snacks[0].y == snacks[i].y) {
end();
return;
}
}             // 判断是否撞上石头
for (i = 0; i < stones.length; i++) {
if (snacks[0].x == stones[i].x && snacks[0].y == stones[i].y) {
end();
return;
}
}             //判断是否撞上食物
var flag = false;
for (i = 0; i < foods.length; i++) {
if (x == foods[i].x && y == foods[i].y) {
flag = true;
foods.splice(i, 1);
}
}
var newSnack = new snack(x, y);
snacks.unshift(newSnack);
if (!flag) {
var p = snacks.pop();
handlePoints(p.x, p.y, 1);
}
document.getElementById(“content”).value = “x:” + snacks[0].x + ” y:” + snacks[0].y + ” length:” + snacks.length;
refresh();
}

function move() {          //移动贪吃蛇
if (moveing == false && switchStatus == 1) {
moveing = true;
if ((currentMove != “right” && changeMove == “left”) || (currentMove == “left” && changeMove == “right”)) {
currentMove = “left”;
judge(snacks[0].x – SNACK_WIDTH, snacks[0].y);
} else if ((currentMove != “down” && changeMove == “up”) || (currentMove == “up” && changeMove == “down”)) {
currentMove = “up”;
judge(snacks[0].x, snacks[0].y – SNACK_HEIGHT);
} else if ((currentMove != “left” && changeMove == “right”)  || (currentMove == “right” && changeMove == “left”)) {
currentMove = “right”;
judge(snacks[0].x + SNACK_WIDTH, snacks[0].y);
} else if ((currentMove != “up” && changeMove == “down”) || (currentMove == “down” && changeMove == “up”)) {
currentMove = “down”;
judge(snacks[0].x, snacks[0].y + SNACK_HEIGHT);
}
changMove = currentMove;
}
moveing = false;
}

function createGround() {              //创建地图
var canvas = document.getElementById(“canvas”);
var draw = canvas.getContext(‘2d’);
//清除原图形
draw.clearRect(0, 0, WIDTH, HEIGHT);
draw.strokeStyle = “red”;
draw.strokeRect(0, 0, WIDTH, HEIGHT);
}

function createFood() {       //创建食物
if (foods.length < TOTAL_FOOD) {
var x = Math.round(Math.random() * (WIDTH / SNACK_WIDTH – 1)) * SNACK_WIDTH;
var y = Math.round(Math.random() * (HEIGHT / SNACK_HEIGHT – 1)) * SNACK_HEIGHT;
if (points.indexOf(x + y * WIDTH) == -1) {
var newFood = new food(x, y);             //alert(newFood.x + “****” + newFood.y);

var canvas = document.getElementById(“canvas”);
var draw = canvas.getContext(‘2d’);
draw.fillStyle = “green”;
draw.fillRect(x, y, SNACK_WIDTH, SNACK_HEIGHT);
foods.push(newFood);
handlePoints(x, y, 0);
}
}
}

function createStone() {          //创建石头
if (stones.length < TOTAL_STONE) {
var x = Math.round(Math.random() * (WIDTH / SNACK_WIDTH – 1)) * SNACK_WIDTH;
var y = Math.round(Math.random() * (HEIGHT / SNACK_HEIGHT – 1)) * SNACK_HEIGHT;
if (points.indexOf(x + y * WIDTH) == -1) {
var newStone = new stone(x, y);
var canvas = document.getElementById(“canvas”);
var draw = canvas.getContext(‘2d’);
draw.fillStyle = “#663300”;
draw.beginPath();
draw.arc(x + SNACK_WIDTH * 0.5, y + SNACK_HEIGHT * 0.5, SNACK_WIDTH * 0.5 + 1, 0, Math.PI * 2, true);
draw.closePath();
draw.fill();
stones.push(newStone);
handlePoints(x, y, 0);
}
}
}

function refresh() {                //刷新场景
var canvas = document.getElementById(“canvas”);
var draw = canvas.getContext(‘2d’);

//清除原图形
draw.clearRect(1, 1, WIDTH – 2, HEIGHT – 2);

//边界
draw.strokeStyle = “red”;
draw.strokeRect(0, 0, WIDTH, HEIGHT);
var i;       /*** 食物   ***/
draw.fillStyle = “green”;
for (i = 0; i < foods.length; i++) {
draw.fillRect(foods[i].x, foods[i].y, SNACK_WIDTH, SNACK_HEIGHT);
}

//石头
draw.fillStyle = “#663300”;
for (i = 0; i < stones.length; i++) {
draw.beginPath();
draw.arc(stones[i].x + SNACK_WIDTH * 0.5, stones[i].y + SNACK_HEIGHT * 0.5, SNACK_WIDTH * 0.5 + 1, 0, Math.PI * 2, true);
draw.closePath();
draw.fill();
}

//贪吃蛇
draw.fillStyle = “blue”;
draw.beginPath();

//圆心x坐标|圆心y坐标|半径|始|PI为圆周率,Math.PI*2为画圆
draw.arc(snacks[0].x + SNACK_WIDTH * 0.5, snacks[0].y + SNACK_HEIGHT * 0.5, SNACK_WIDTH * 0.5 + 1, 0, Math.PI * 2, true);
draw.closePath();
draw.fill();
for (i = 1; i < snacks.length; i++) {
draw.fillRect(snacks[i].x, snacks[i].y, SNACK_WIDTH, SNACK_HEIGHT);
}
}

//游戏开始
function play() {
createGround();
for (var i = 2; i > 0; i–) {
var newSnack = new snack(SNACK_WIDTH * i, SNACK_HEIGHT);
snacks.push(newSnack);
handlePoints(newSnack.x, newSnack.y, 0);
}
refresh();
document.onkeydown = keyDown;
timeMoveId = setInterval(move, TIME_MOVE);
timeFoodId = setInterval(createFood, TIME_FOOD);
timeStoneId = setInterval(createStone, TIME_STONE);
}

//游戏结束
function end() {
clearInterval(timeMoveId);
clearInterval(timeFoodId);
clearInterval(timeStoneId);
switchStatus = 0;
changeMove = “right”;
currentMove = “right”;
points.length = 0;
snacks.length = 0;
foods.length = 0;
stones.length = 0;
moveing = false;
document.getElementById(“switch”).value = “开始”;
document.getElementById(“content”).value = “游戏结束”;
alert(“游戏结束”);
}

html游戏三:打砖块

// JavaScript Document
/*
1.需要哪些元素
小球 挡板 砖块区域 初始x位置 初始y位置
2.要有那些行为
初始化init
init用来存放初始化方法
如果实例化对象调用所有方法很麻烦,所以一次性解决
创建砖块creatBrick
for循环生成砖块
计算每一个砖块初始化top和left
计算金字塔中线位置
初始化小球
初始化小球x方向移动向量
初始化小球y方向移动向量
初始化小球宽度和高度
初始化小球开始运动事件
初始化小球位置 x,y
初始化挡板
初始化挡板位置 x,y
初始化鼠标监听事件
挡板的移动
挡板中央跟随鼠标x方向移动
挡板运动边界 左 右
小球的移动
小球移动方法 requestAnimationFrame
小球x y 向量自增
碰撞检测{
1:小球和浏览器边框的碰撞
反弹 x||y
2:小球和挡板的碰撞
反弹 y
3.小球和砖块的碰撞
反弹 y && 移除砖块
}
*/
var oBall = document.querySelector(“#ball”);     //球
var oWard = document.querySelector(“#ward”);      //挡板
var oScore = document.querySelector(‘#score’);       //计分板
var oWrap = document.querySelector(‘#wrap’);        //砖块区域
var over = document.querySelector(‘#gameover’);        //结束
function Breakout(ball, ward, score, wrap, over) {     //打砖块小游戏对象 构造函数
this.ball = ball;
this.ward = ward;
this.scores = score;
this.wrap = wrap;
this.over = over;
this.x = 0;
this.y = 0;
this.score = 0;
}

Breakout.prototype = {     //原型方法
init: function () {      //初始化系统
this.ballstar();      //初始化小球
this.creatBrick();       //创建砖块
this.wardMove();        //挡板移动
},
creatBrick: function () {          //砖块初始化
var x = document.documentElement.offsetWidth / 2 – document.documentElement.offsetWidth * .05;      //设置居中位置
w = 45 * 2;     //设置横向间距基准值
h = 15 * 2;       //设置纵向间距基准值
for (var i = 1; i <= 8; i++) {    //循环生成div 8层
for (var j = 0; j < i * 2 – 1; j++) {    //每一层的砖块个数=层数*2-1
var brick = document.createElement(“div”);
brick.style.top = (i – 1) * h + ‘px’;
brick.style.left = x – (i * w) + (j * w) + ‘px’;
this.wrap.appendChild(brick);
}
}
},
wardMove: function () {       //挡板初始化
this.ward.style.top = window.innerHeight – 180 + ‘px’;      //初始化挡板的top位置
this.ward.style.left = this.x – 60 + ‘px’;      //初始化挡板的left位置居中
this.addEvent(document, ‘mousemove’, this.mouseMove.bind(this));        //监听鼠标移动
},
ballstar: function () {      //小球初始化
var This = this;
this.y = window.innerHeight – 200;      //初始化坐标X的位置 窗口底部上移200px
this.x = window.innerWidth / 2;    //初始化坐标Y的位置 窗口中间部位
this.ball.style.top = this.y + ‘px’;      //初始化小球的top值为y
this.ball.style.left = this.x + ‘px’;        //初始化小球的left值为x
this.ball.speed = 10;      //初始化小球的速度
this.ball.width = 15;             //初始化小球的宽度
this.ball.height = 15;        //初始化小球的高度
document.onclick = function () {         //点击开始游戏,小球运动
This.ballMove();           //小球移动
}

},
//挡板移动
mouseMove: function (e) {        //鼠标移动,挡板跟随鼠标运动
e = e || window.event;       //事件对象兼容性处理
var _left = e.pageX – this.ward.offsetWidth / 2;        //保证鼠标移动,挡板中间位置同步鼠标位置
_left = Math.min(window.innerWidth – this.ward.offsetWidth, _left);         //挡板向右移动不能超过屏幕右边界
_left = Math.max(0, _left);      //挡板向左移动不能超过屏幕左边界
this.ward.style.left = _left + ‘px’;          //通过设置挡板left值实现挡板移动
},
ballMove: function () {         //小球开始运动
document.onclick = null;       //先清除document的点击事件防止一直重置运动
this.ball.xspeed = this.ball.speed;          //初始化小球x运动速度和方向 +为往左 -为往右
this.ball.yspeed = -this.ball.speed;         //初始化小球y运动速度和方向 +为往上 -为往下
function auto() {          //运动函数 auto 通过requestAnimationFrame递归调 用实现循环
this.x += this.ball.xspeed;        //x代表当前横向位置 += 横向移动速度 10 每一次都在自己原先的位置基础上+10
this.y += this.ball.yspeed;       //y代表当前横向位置 += 横向移动速度 10 每一次都在自己原先的位置基础上+10
this.crash();          //碰撞检测
this.ball.style.left = this.x + ‘px’;       //小球运动赋值 x轴运动
this.ball.style.top = this.y + ‘px’;            //小球运动赋值 y轴运动
requestAnimationFrame(auto.bind(this));           //原生js动画 根据cpu运算速度来实现更新
}
auto.call(this);
},
crash: function () {
var maxWidth = window.innerWidth – this.ball.offsetWidth;       //浏览器左边界=浏览器宽度-球的宽度
var maxHeight = window.innerHeight – this.ball.offsetHeight;         //浏览器右边界=浏览器高度-球的高度
if (this.y >= maxHeight) {            //小球掉下去之后,游戏结束
this.gameOver();
}
if (this.x >= maxWidth) {
this.ball.xspeed *= -1;          //小球碰到右边墙壁后 横向移动速度取反 往返方向移动
this.x = maxWidth;           //重置小球位置
}
if (this.x < 0) {           //碰到左边墙 重置横向移动速度 并且重置横向位置 为0
this.ball.xspeed = this.ball.speed;
this.x = 0;
}
if (this.y < 0) {           //碰到上边墙壁之后 重置纵向移动速度 以及纵向位置 为0
this.ball.yspeed = this.ball.speed;
this.y = 0;
}
//挡板碰撞检测 xweizhi
if (Math.abs(this.x – (this.ward.offsetLeft + (this.ward.clientWidth / 2))) < 60 && Math.abs(this.y – this.ward.offsetTop – 30) < 45) {
var color = this.ranColor();
this.ward.style.background = color;
this.ball.yspeed *= -1;
this.y = this.ward.offsetTop – 40;
}
for (var i = this.wrap.children.length – 1; i >= 0; i–) {
var ballMx = this.ball.offsetLeft + (this.ball.width / 2);
var ballMy = this.ball.offsetTop + (this.ball.height / 2);
var brickMx = (this.wrap.children[i].offsetLeft + this.wrap.offsetLeft) + (45 / 2);
var brickMy = (this.wrap.children[i].offsetTop + this.wrap.offsetTop) + (15 / 2);
if (Math.abs(ballMx – brickMx) <= 45 && Math.abs(ballMy – brickMy) <= 15) {
this.ball.yspeed *= -1;
this.y = brickMy;
this.wrap.removeChild(this.wrap.children[i]);
if (this.wrap.children.length == 0) {
this.gameOver();
}
this.scoreChange();
}
}
},
scoreChange: function () {
this.score++;
this.scores.innerHTML = this.score + ‘分’;
},
gameOver: function () {
this.over.style.display = ‘block’;
this.over.children[0].innerHTML = ‘总分:’ + this.score;
var all = document.querySelectorAll(‘*’);
for (var i = 0; i < all.length; i++) {
all[i].style.cursor = ‘auto’
}
this.ward.style.display = ‘none’;
this.ball.style.display = ‘none’;
this.over.children[1].onclick = function () {
window.location.reload();
}
},
/* getStyle: function (ele, curr) {         //获取属性值
return ele.currentStyle ? parseInt(ele.currentStyle[curr]) : parseInt(getComputedStyle(ele, null)[curr]);
},*/
addEvent: function (element, e, fn) {         //事件监听
return element.attachEvent ? element.attachEvent(‘on’ + e, fn) : element.addEventListener(e, fn, false);
},
ranColor: function () {          //随机颜色
var color = ‘#’;
for (var i = 0; i < 6; i++) {
color += ‘0123456789abcdef’ [Math.floor(Math.random() * 16)]
}
return color;
},
}

var breakout = new Breakout(oBall, oWard, oScore, oWrap, over);
breakout.init();

html游戏二:2048

// JavaScript Document
var arr;
function init() {
arr = new Array(4);
for (i = 0; i < arr.length; i++) {
arr[i] = [0, 0, 0, 0];
}

//初始化游戏页面,需要在表格中随机生成一个2,一个4

var x1, x2, y1, y2;
x1 = Math.round(Math.random() * 3);
y1 = Math.round(Math.random() * 3);
arr[x1][y1] = 2;
while (true) {
x2 = Math.round(Math.random() * 3);
y2 = Math.round(Math.random() * 3);
if (x1 != x2 || y1 != y2) {
arr[x2][y2] = 4;
break;
}
}
display();
show();
}

function show() {        //show()方法用于显示获胜提示以及得分
var count = 0;
for (i = 0; i < arr.length; i++) {
for (j = 0; j < arr.length; j++) {
count += arr[i][j];
var num = arr[i][j];
var td = document.getElementById(i + “” + j);
if (num == 2048) {
var p = document.getElementById(“show”);
p.innerHTML = “”;
p.innerHTML = “恭喜你!已经获得2048胜利!可以继续挑战4096!”;
}
if (num == 4096) {
var p = document.getElementById(“show”);
p.innerHTML = “”;
p.innerHTML = “恭喜你!已经获得4096胜利!”;
}

}
}
var p = document.getElementById(“score”);
p.innerHTML = “”;
p.innerHTML = “成绩: ” + count;
}

function display() {
for (i = 0; i < arr.length; i++) {
for (j = 0; j < arr.length; j++) {
var td = document.getElementById(i + “” + j);     //查找对应下标的元素

if (arr[i][j] != 0) {     //将对应的数据显示到元素中
td.innerHTML = arr[i][j];      //有效数据
} else {
td.innerHTML = ” “;
}
}
}
}
window.onkeydown = function () {
var code = event.keyCode;
switch (code) {
case 37:       //方向键←
onleft();
show();
break;
case 38:        //方向键↑
ontop();
show();
break;
case 39:        //方向键→
onright();
show();
break;
case 40:        //方向键↓
onbottom();
show();
break;
}
}

function onleft() {      //onleft() 方法用于按键盘方向键←对游戏的控制
for (i = 0; i < arr.length; i++) {            //将每个数组中的有效数据向左移动
var temp = new Array(0, 0, 0, 0);       //创建一个临时数组, 用于存储当前行的有效数据
var index = 0;       //记录每次有效数据存储的位置
for (j = 0; j < arr.length; j++) {
if (arr[i][j] != 0) {
temp[index] = arr[i][j];
index++;
}
}
for (j = 0; j < temp.length – 1; j++) {     //相邻相同数据, 相加 , 后续数据前移一位
if (temp[j] == temp[j + 1]) {
temp[j] *= 2;
var k = j + 1;                     //记录住第一个要被覆盖的下标
while (k < arr.length – 1) {
temp[k++] = temp[k];

}
temp[temp.length – 1] = 0;   //两个数字产生合并 , 最后一个位置赋值为0
}
}
arr[i] = temp;
}

random();     //随机产生一个2或者4 放在在一个空的位置
display();
}
function ontop() {       //ontop() 方法用于按键盘方向键↑对游戏的控制
for (i = 0; i < arr.length; i++) {
var temp = new Array(0, 0, 0, 0);
var index = 0;
for (j = 0; j < arr.length; j++) {
if (arr[j][i] != 0) {
temp[index] = arr[j][i];
index++;
}
}
for (j = 0; j < temp.length – 1; j++) {
if (temp[j] == temp[j + 1]) {
temp[j] *= 2;
var k = j + 1;
while (k < arr.length – 1) {
temp[k++] = temp[k];
}
temp[temp.length – 1] = 0;
}
}
for (j = 0; j < arr.length; j++) {
arr[j][i] = temp[j];
}
}

random();
display();

}

function onbottom() {
for (i = 0; i < arr.length; i++) {
var temp = new Array(0, 0, 0, 0);
var index = 3;
for (j = 3; j >= 0; j–) {
if (arr[j][i] != 0) {
temp[index] = arr[j][i];
index–;
}
}
for (j = 3; j > 0; j–) {
if (temp[j] == temp[j – 1]) {
temp[j] *= 2;
var k = j – 1;
while (k > 0) {
temp[k–] = temp[k];
}
temp[0] = 0;
}
}
for (j = 3; j >= 0; j–) {
arr[j][i] = temp[j];
}
}

random();
display();
}

function onright() {
for (i = 0; i < arr.length; i++) {
var temp = new Array(0, 0, 0, 0);
var index = 3;
for (j = 3; j >= 0; j–) {
if (arr[i][j] != 0) {
temp[index] = arr[i][j];
index–;
}
}
for (j = 3; j > 0; j–) {
if (temp[j – 1] == temp[j]) {
temp[j] *= 2;
var k = j – 1;
while (k > 0) {
temp[k–] = temp[k];
}
temp[0] = 0;
}
}
arr[i] = temp;
}

random();
display();
}

function random() {          // 用于记录使用可以继续产生随机数字
var flag = false;
for (i = 0; i < arr.length; i++) {     //循环遍历所有数据, 查询是否存在0 , 如果不存在,则直接结束游戏!
for (j = 0; j < arr.length; j++) {
if (arr[i][j] == 0) {
flag = true;
break;
}
}
}
if (!flag) {
alert(“抱歉, 此时的数字排列无法继续进行数字叠加,游戏结束!”);
return;
}
var x, y;          //产生一个随机位置
while (true) {
x = Math.round(Math.random() * 3);
y = Math.round(Math.random() * 3);
if (arr[x][y] == 0) {
break;
}
}
while (true) {        //产生一个随机数字
var num = Math.round(Math.random() * 6);
if (num == 2 || num == 4) {
arr[x][y] = num;
break;
}
}
}