Игры
Крестики-нолики
Код:
<html> <head> <title>Игра крестики-нолики</title> </head> <body> <p align=center><br> <SCRIPT language=JavaScript> <!-- step = 0; diff=3; // change board when button is clicked function clear_all(form) { step = 0; for (i=0;i<9; ++i) { position="a"+i; form[position].value=""; } } // change board when button is clicked function clickit(field) { if (step == -1) {alert("Reset to play again"); return;} position=field.name.substring(1,2,1); position = 'a'+position; if (field.form[position].value !="") { alert("Can't go there"); return;} field.form[position].value="X"; if (eval_pos(field.form)) { field.form.output.value="Вы победили!"; step = -1; return; } position=get_move(field.form); field.form.output.value='I moved to ' + position.substring(1,2,1); if (position=="") { field.form.output.value="Ничья."; step = -1; return; } field.form[position].value="O"; if (eval_pos(field.form)) { field.form.output.value="Вы проиграли!"; step = -1; } } // see if there is a winner function eval_pos(form) { if ((form.a0.value!="" && form.a0.value==form.a3.value && form.a0.value==form.a6.value)|| (form.a0.value!="" && form.a0.value==form.a1.value && form.a0.value==form.a2.value) || (form.a0.value!="" && form.a0.value==form.a4.value && form.a0.value==form.a8.value) || (form.a1.value!="" && form.a1.value==form.a4.value && form.a1.value==form.a7.value) || (form.a2.value!="" && form.a2.value==form.a5.value && form.a2.value==form.a8.value) || (form.a2.value!="" && form.a2.value==form.a4.value && form.a2.value==form.a6.value) || (form.a3.value!="" && form.a3.value==form.a4.value && form.a3.value==form.a5.value) || (form.a6.value!="" && form.a6.value==form.a7.value && form.a6.value==form.a8.value)) return true; else return false; } function f(a) { if (a == "") return "."; else return a; } // get position for move. function comp_move(form,player,weight,depth) { var cost; var bestcost=-2; var position; var newplayer; if (player=="X") newplayer="O"; else newplayer="X"; if (depth==diff) return 0; if (eval_pos(form)) return 1; for (var i=0; i<9; ++i) { position='a'+i; if (form[position].value != "") continue; form[position].value=player; cost = comp_move(form,newplayer, -weight, depth+1); if (cost > bestcost) { bestcost=cost; if (cost==1) i=9; } form[position].value=""; } if (bestcost==-2) bestcost=0; return(-bestcost); } // get position for move. function get_move(form) { var cost; var bestcost=-2; bestmove=""; // don't think about first move. if (step++ == 0) if (form.a4.value=="") return "a4"; else if (form.a0.value=="") return "a0"; for (var i=0; i<9; ++i) { localposition='a'+i; if (form[localposition].value != "") continue; form[localposition].value="O"; cost=comp_move(form,"X", -1, 0); if (cost > bestcost) { if (cost==1) i=9; bestmove=localposition; bestcost=cost; } form[localposition].value=""; } return bestmove; } // complain if user attempts to change board function complain(field) { field.form.output.focus(); // put focus eleswhere alert("Don't change the game fields directly!"); } // the end // --> </SCRIPT> <form> <P> <input name=a0 onfocus=complain(this) size=1> <input name=b0 onclick=clickit(this) type=button> <input name=a1 onfocus=complain(this) size=1> <input name=b1 onclick=clickit(this) type=button> <input name=a2 onfocus=complain(this) size=1> <input name=b2 onclick=clickit(this) type=button> <br> <input name=a3 onfocus=complain(this) size=1> <input name=b3 onclick=clickit(this) type=button> <input name=a4 onfocus=complain(this) size=1> <input name=b4 onclick=clickit(this) type=button> <input name=a5 onfocus=complain(this) size=1> <input name=b5 onclick=clickit(this) type=button> <br><input name=a6 onfocus=complain(this) size=1> <input name=b6 onclick=clickit(this) type=button> <input name=a7 onfocus=complain(this) size=1> <input name=b7 onclick=clickit(this) type=button> <input name=a8 onfocus=complain(this) size=1> <input name=b8 onclick=clickit(this) type=button> <br><br><br> Message: <input name=output><br><br> Сложность игры : <SELECT name=difficulty onchange=diff=form.difficulty[form.difficulty.selectedIndex].value; size=1> <option value=1>Очень лёгкая</option> <option value=2>Просто</option> <option selected value=3>Нормально</option> <option value=4>Сложно (Компьютер долго думает)</option></SELECT><br> <input onclick="if (!step++) this.form.a4.value='O';" type=button value="Компьютер ходит первым"><br> <input onclick=clear_all(this.form) type=reset value=Рестарт> </P></form> </body> </html>
Морской бой
Код:
<html> <head> <style type="text/css"> .intro { FONT-SIZE: 10pt; FONT-STYLE: italic} .heading { FONT-FAMILY: sans-serif; FONT-SIZE: 14pt; FONT-WEIGHT: bold } .title { BACKGROUND-COLOR: navy; COLOR: white; FONT-FAMILY: sans-serif; FONT-SIZE: 18pt; FONT-WEIGHT: bold; TEXT-ALIGN: center } #adv { HEIGHT: 60px; LEFT: 0px; TOP: 0px; WIDTH: 468px } </style> </HEAD> <body> <script language="JavaScript"> <!-- Begin /* Information used to draw the ships */ var ship = [[[1,5], [1,2,5], [1,2,3,5], [1,2,3,4,5]], [[6,10], [6,7,10], [6,7,8,10], [6,7,8,9,10]]]; /* Information used to draw sunk ships */ var dead = [[[201,203], [201,202,203], [201,202,202,203], [201,202,202,202,203]], [[204,206], [204,205,206], [204,205,205,206], [204,205,205,205,206]]]; /* Information used to describe ships */ var shiptypes = [["Минер",2,4],["Фрегат",3,4],[ "Крейсер",4,2],[ "Боевой Корабль",5,1]]; var gridx = 16, gridy = 16; var player = [], computer = [], playersships = [], computersships = []; var playerlives = 0, computerlives = 0, playflag=true, statusmsg=""; /* Function to preload all the images, to prevent delays during play */ var preloaded = []; function imagePreload() { var i,ids = [1,2,3,4,5,6,7,8,9,10,100,101,102,103,201,202,203,204,205,206]; window.status = "Идет загруска картинок....."; for (i=0;i<ids.length;++i) { var img = new Image, name = "img/batt"+ids[i]+".gif"; img.src = name; preloaded[i] = img; } window.status = ""; } /* Function to place the ships in the grid */ function setupPlayer(ispc) { var y,x; grid = []; for (y=0;y<gridx;++y) { grid[y] = []; for (x=0;x<gridx;++x) grid[y][x] = [100,-1,0]; } var shipno = 0; var s; for (s=shiptypes.length-1;s>=0;--s) { var i; for (i=0;i<shiptypes[s][2];++i) { var d = Math.floor(Math.random()*2); var len = shiptypes[s][1], lx=gridx, ly=gridy, dx=0, dy=0; if ( d==0) { lx = gridx-len; dx=1; } else { ly = gridy-len; dy=1; } var x,y,ok; do { y = Math.floor(Math.random()*ly); x = Math.floor(Math.random()*lx); var j,cx=x,cy=y; ok = true; for (j=0;j<len;++j) { if (grid[cy][cx][0] < 100) { ok=false; break; } cx+=dx; cy+=dy; } } while(!ok); var j,cx=x,cy=y; for (j=0;j<len;++j) { grid[cy][cx][0] = ship[d][s][j]; grid[cy][cx][1] = shipno; grid[cy][cx][2] = dead[d][s][j]; cx+=dx; cy+=dy; } if (ispc) { computersships[shipno] = [s,shiptypes[s][1]]; computerlives++; } else { playersships[shipno] = [s,shiptypes[s][1]]; playerlives++; } shipno++; } } return grid; } /* Function to change an image shown on a grid */ function setImage(y,x,id,ispc) { if ( ispc ) { computer[y][x][0] = id; document.images["pc"+y+"_"+x].src = "img/batt"+id+".gif"; } else { player[y][x][0] = id; document.images["ply"+y+"_"+x].src = "img/batt"+id+".gif"; } } /* Function to insert HTML source for a grid */ function showGrid(ispc) { var y,x; for (y=0;y<gridy;++y) { for (x=0;x<gridx;++x) { if ( ispc ) document.write ('<a href="" OnClick="gridClick('+y+','+x+');return false;"><img name="pc'+y+'_'+x+'" src="img/batt100.gif" width=16 height=16 border=0></a>'); else document.write ('<img name="ply'+y+'_'+x+'" src="img/batt'+player[y][x][0]+'.gif" width=16 height=16 border=0>'); } document.write('<img src=img/dot.gif width=1 height=16><br>'); } polewidth = 1 + gridx * 16; document.write('<img src=img/dot.gif width='+polewidth+' height=1><br>'); } /* Handler for clicking on the grid */ function gridClick(y,x) { if ( playflag ) { if (computer[y][x][0] < 100) { setImage(y,x,103,true); var shipno = computer[y][x][1]; if ( --computersships[shipno][1] == 0 ) { sinkShip(computer,shipno,true); //alert("You sank my "+shiptypes[computersships[shipno][0]][0]+"!"); updateStatus(); if ( --computerlives == 0 ) { alert("Вы победили!"); playflag = false; } } if ( playflag ) computerMove(); } else if (computer[y][x][0] == 100) { setImage(y,x,102,true); computerMove(); } } } /* Function to make the computers move. Note that the computer does not cheat, oh no! */ function computerMove() { var x,y,pass; var sx,sy; var selected = false; /* Make two passes during 'shoot to kill' mode */ for (pass=0;pass<2;++pass) { for (y=0;y<gridy && !selected;++y) { for (x=0;x<gridx && !selected;++x) { /* Explosion shown at this position */ if (player[y][x][0]==103) { sx=x; sy=y; var nup=(y>0 && player[y-1][x][0]<=100); var ndn=(y<gridy-1 && player[y+1][x][0]<=100); var nlt=(x>0 && player[y][x-1][0]<=100); var nrt=(x<gridx-1 && player[y][x+1][0]<=100); if ( pass == 0 ) { /* On first pass look for two explosions in a row - next shot will be inline */ var yup=(y>0 && player[y-1][x][0]==103); var ydn=(y<gridy-1 && player[y+1][x][0]==103); var ylt=(x>0 && player[y][x-1][0]==103); var yrt=(x<gridx-1 && player[y][x+1][0]==103); if ( nlt && yrt) { sx = x-1; selected=true; } else if ( nrt && ylt) { sx = x+1; selected=true; } else if ( nup && ydn) { sy = y-1; selected=true; } else if ( ndn && yup) { sy = y+1; selected=true; } } else { /* Second pass look for single explosion - fire shots all around it */ if ( nlt ) { sx=x-1; selected=true; } else if ( nrt ) { sx=x+1; selected=true; } else if ( nup ) { sy=y-1; selected=true; } else if ( ndn ) { sy=y+1; selected=true; } } } } } } if ( !selected ) { /* Nothing found in 'shoot to kill' mode, so we're just taking potshots. Random shots are in a chequerboard pattern for maximum efficiency, and never twice in the same place */ do{ sy = Math.floor(Math.random() * gridy); sx = Math.floor(Math.random() * gridx/2)*2+sy%2; } while( player[sy][sx][0]>100 ); } if (player[sy][sx][0] < 100) { /* Hit something */ setImage(sy,sx,103,false); var shipno = player[sy][sx][1]; if ( --playersships[shipno][1] == 0 ) { sinkShip(player,shipno,false); //alert("I sank your "+shiptypes[playersships[shipno][0]][0]+"!"); if ( --playerlives == 0 ) { knowYourEnemy(); alert("Вы проиграли!"); playflag = false; } } } else { /* Missed */ setImage(sy,sx,102,false); } } /* When whole ship is hit, show it using changed graphics */ function sinkShip(grid,shipno,ispc) { var y,x; for (y=0;y<gridx;++y) { for (x=0;x<gridx;++x) { if ( grid[y][x][1] == shipno ) if (ispc) setImage(y,x,computer[y][x][2],true); else setImage(y,x,player[y][x][2],false); } } } /* Show location of all the computers ships - when player has lost */ function knowYourEnemy() { var y,x; for (y=0;y<gridx;++y) { for (x=0;x<gridx;++x) { if ( computer[y][x][0] == 103 ) setImage(y,x,computer[y][x][2],true); else if ( computer[y][x][0] < 100 ) setImage(y,x,computer[y][x][0],true); } } } /* Show how many ships computer has left */ function updateStatus() { var f=false,i,s = "Корабли компьютера: "; for (i=0;i<computersships.length;++i) { if (computersships[i][1] > 0) { if (f) s=s+", "; else f=true; s = s + shiptypes[computersships[i][0]][0]; } } if (!f) s = s + "ничего не осталось"; statusmsg = s; window.status = statusmsg; } function setStatus() { window.status = statusmsg; } function NewGame() { var rndnum = Math.round(Math.random() * 100000); oldlocation = window.location; window.location= "index.htm?"+ rndnum; } var ie4 = (document.all) ? true : false; var nn4 = (document.layers) ? true : false; /* Start the game! */ imagePreload(); player = setupPlayer(false); computer = setupPlayer(true); document.write("<center><table><tr><td align=center>Флот Компьютера</td>"+ "<td align=center>Ваш Флот</td></tr><tr><td>"); showGrid(true); document.write("</td><td>"); showGrid(false); document.write("</td></tr></table></center>"); document.write("<center><form><INPUT style=\"color: #00cc00; background-color: #000000; border-color: #00cc00;\" type=\"submit\" VALUE=\"Новая Игра !\"></form></center>"); updateStatus(); setInterval("setStatus();", 500); // End --> </script> </div> </body> </html>
Пирамида
Код:
<html> <head> <title>Пирамида</title> </head> <body> <script LANGUAGE="JavaScript"> // change this to where you upload the images to your site imgdir = ""; function preload() { this.length = preload.arguments.length; for (var i = 0; i < this.length; i++) { this[i] = new Image(); this[i].src = imgdir + preload.arguments[i]; } } var pics = new preload("disk1.gif","disk2.gif", "disk3.gif","disk4.gif","disk5.gif","disk6.gif", "disk7.gif","pole.gif", "disk1h.gif","disk2h.gif", "disk3h.gif","disk4h.gif","disk5h.gif","disk6h.gif", "disk7h.gif"); var selectedr = null; var selectedc = null; var maxposts = 3; var maxdisks = 7; var all_posts = 3; var startpost = 1; var endpost = (startpost-1 < 0 ? maxposts-1 : startpost-1); var disks = 7; var imgwidth = 160; var imgheight = 14; var game_is_over = false; var show_messages = false; var board = new Array(maxposts); board[0] = new Array(maxdisks + 1); board[1] = new Array(maxdisks + 1); board[2] = new Array(maxdisks + 1); function initboard(startpost, disks) { var len = board[0].length; selectedc = null; selectedr = null; game_is_over = false; endpost = (startpost-1 < 0 ? maxposts-1 : startpost-1); for (i = 0; i < len; i++) { board[0][i] = 0; board[1][i] = 0; board[2][i] = 0; } for (i = len-disks, j = 0; i < len; i++, j++) { board[startpost][i] = len - j - 1; } } function drawall() { for (j=0; j<board.length; j++) { for (i=0; i<board[j].length; i++) { draw(j,i, getName( board[j][i])); } } message("Вы можете уже играть ! Вам нужно переместить пирамиду на одну из трех полочек (любую)!"); } function restart(start) { startpost = start; disks = document.forms[0].disc.options[document.forms[0].disc.selectedIndex].text; initboard(startpost,disks); drawall(); theAnim = new Animation(); } initboard(startpost, disks); function getName( num ) { if (num == 0) return "post.gif"; return "disk" + num + ".gif"; } function message(str, force) { if (force || !game_is_over && !show_messages) document.disp.message.value = str; } function messageadd(str) { if (!game_is_over) document.disp.message.value = document.disp.message.value + "\n" + str; } function isempty(num) { for (i = 0; i < board[num].length; i++) { if ( board[num][i] != 0) return false; } return true; } function topmost(num) { for (i = 0; i < board[num].length; i++) { if (board[num][i] != 0) return i; } return -1; } function ispost(i,j) { return (board[j][i] == 0); } function istopdisk(i,j) { return (board[j][i-1] == 0); } function drawboard() { document.writeln("<div align=center><center><table cellspacing=0 cellpadding=0 border=0>"); document.write("<tr>"); for (j = 0; j < board.length; j++) { document.write("<td>"); document.write("<a href='javascript:clicked("+0+","+j+")'><img src='" + imgdir + "posttop.gif' border=0></a><br>"); for (i=0; i< board[0].length; i++) { document.write("<a href='javascript:clicked("+i+","+j+")'>"); document.write("<img src='" + imgdir + getName(board[j][i]) + "' name='pos"+ j + i + "' border=0><br>"); document.write("</a>"); } document.writeln("</td>"); } document.write("</tr></table>"); document.write("<form name='disp'><textarea name='message' wrap=virtual rows=2 cols=40></textarea><br><br>" + "<font face=\"MS Sans Serif\" size=\"1\">Всего Дисков: </font><select name=\"disc\" size=1 style=\"font-family: MS Sans Serif; font-size: 1\"><option>3<option>4<option>5<option>6<option selected>7</select><input " +"type=button value=\"Начать игру\" onClick=\"restart(startpost);\" size=1 style=\"font-family: MS Sans Serif; font-size: 1\"></form>"); } function draw(x,y,name) { document.images["pos"+x+""+y].src = imgdir + name; } function animate(x,y,name) { theAnim.addFrame( "pos"+x+""+y, imgdir + name); } function clicked(i,j) { document.forms[0].message.focus(); // get rid of annoying outline in MSIE document.forms[0].message.blur(); if (game_is_over) restart(startpost = endpost); if (!isselection() && ispost(i,j)) { message(":)"); return; } if (!ispost(i,j)) { toggle(j); return; }; if (ispost(i,j) && selectedc == j) { message(":)"); return; } if (!legalmove(j)) { message(":)"); return; } move(j); return; } function legalmove(j) { if (isempty(j)) return true; return (board[j][topmost(j)] < board[selectedc][selectedr]); } function isselection() { return selectedc != null; } function toggle( num ) { var toppos = topmost(num); if (selectedc == num && selectedr == toppos) { selectedc = null; selectedr = null; animate(num,toppos,"disk" + board[num][toppos] + ".gif"); message(":)"); return; } if (isselection()) { animate(selectedc,selectedr,"disk" + board[selectedc][selectedr] + ".gif"); } selectedc = num; selectedr = toppos; animate(num,toppos,"disk" + board[num][toppos] + "h.gif"); message(":)"); } function move( num ) { var toppos = (!isempty(num) ? topmost(num) : board[num].length); board[num][toppos-1] = board[selectedc][selectedr]; board[selectedc][selectedr] = 0; animate(selectedc,selectedr,"post.gif"); animate(num,toppos-1,"disk" + board[num][toppos-1] + ".gif"); selectedc = null; selectedr = null; message(":)"); game_over(); } function hanoi(no_of_disks, start_post, goal_post) { if (no_of_disks > 0) { var free_post = all_posts - start_post - goal_post; hanoi (no_of_disks - 1, start_post, free_post); show_messages = true; toggle(start_post); move(goal_post); show_messages = false; hanoi (no_of_disks - 1 , free_post, goal_post); game_over(true); } } function game_over(forceMsg) { var filledpost = null; var val = 0; for (k = 0; k < board.length; k++) { val += ( isempty(k) ? 1 : 0 ); if (!isempty(k)) filledpost = k; } if (val == 2 && isempty(startpost)) { message("Вы выграли! А ещё будете играть ?", forceMsg); game_is_over = true; endpost = filledpost; } return game_is_over; } // // Animation functions // function Animation() { this.imageNum = new Array(); // Array of indicies document.images to be changed this.imageSrc = new Array(); // Array of new srcs for imageNum array this.frameIndex = 0; // the frame to play next this.alreadyPlaying = false; // semaphore to ensure we play smoothly this.getFrameCount = getframecount; // the total numebr of frame so far this.moreFrames = moreframes; // tells us if there are more frames to play this.addFrame = addframe; // add a frame to the animation this.drawNextFrame = drawnextframe; // draws the next frame this.startAnimation = startanimation; // start the animation if necessary } function getframecount() { return this.imageNum.length; } function moreframes() { return this.frameIndex < this.getFrameCount(); } function startanimation() { if (!this.alreadyPlaying) { theAnim.alreadyPlaying = true; setTimeout('theAnim.drawNextFrame()',5); } } function addframe(num, src) { var theIndex = theAnim.imageNum.length; theAnim.imageSrc[theIndex] = src; theAnim.imageNum[theIndex] = num; theAnim.startAnimation(); } function drawnextframe() { if (theAnim.moreFrames()) { document.images[ theAnim.imageNum[theAnim.frameIndex] ].src = theAnim.imageSrc[theAnim.frameIndex]; theAnim.frameIndex++; setTimeout('theAnim.drawNextFrame()', 30); } else { theAnim.alreadyPlaying = false; } } drawboard(); var theAnim = new Animation(); message("Вы можете уже играть ! Вам нужно переместить пирамиду на одну из трех полочек (любую)!"); document.disp.message.value = "Вы можете уже играть ! Вам нужно переместить пирамиду на одну из трех полочек (любую)!"; var ie4 = (document.all) ? true : false; var nn4 = (document.layers) ? true : false; // End --> </script> <p> </p> </body> </html>