Редактирование: Игра "Змейка"

Перейти к: навигация, поиск

Внимание! Вы не авторизовались на сайте. Ваш IP-адрес будет публично видимым, если вы будете вносить любые правки. Если вы войдёте или создадите учётную запись, правки вместо этого будут связаны с вашим именем пользователя, а также у вас появятся другие преимущества.

Правка может быть отменена. Пожалуйста, просмотрите сравнение версий, чтобы убедиться, что это именно те изменения, которые вас интересуют, и нажмите «Записать страницу», чтобы изменения вступили в силу.
Текущая версия Ваш текст
Строка 2: Строка 2:
 
В этой игре пользователь управляет змейкой, которая ползает по плоскости, ограниченной стенками, и собирает еду, избегая столкновения с собственным хвостом и краями игрового поля.
 
В этой игре пользователь управляет змейкой, которая ползает по плоскости, ограниченной стенками, и собирает еду, избегая столкновения с собственным хвостом и краями игрового поля.
  
Исполнители: [http://tm.spbstu.ru/%D0%94%D0%B5%D0%BC%D0%B8%D0%BD%D0%B0_%D0%9A%D1%81%D0%B5%D0%BD%D0%B8%D1%8F Демина К.В.], [http://tm.spbstu.ru/%D0%9F%D1%80%D0%BE%D1%85%D0%BE%D1%80%D0%B5%D0%BD%D0%BA%D0%BE%D0%B2%D0%B0_%D0%98%D1%80%D0%B8%D0%BD%D0%B0 Прохоренкова И.Г.], [http://tm.spbstu.ru/%D0%9C%D0%B0%D0%BB%D1%8B%D1%88%D0%B5%D0%B2%D0%B0_%D0%92%D0%B5%D1%80%D0%BE%D0%BD%D0%B8%D0%BA%D0%B0 Малышева В.Н.]
+
Исполнители: [http://tm.spbstu.ru/%D0%94%D0%B5%D0%BC%D0%B8%D0%BD%D0%B0_%D0%9A%D1%81%D0%B5%D0%BD%D0%B8%D1%8F Демина Ксения], [http://tm.spbstu.ru/%D0%9F%D1%80%D0%BE%D1%85%D0%BE%D1%80%D0%B5%D0%BD%D0%BA%D0%BE%D0%B2%D0%B0_%D0%98%D1%80%D0%B8%D0%BD%D0%B0 Прохоренкова И.Г.], [http://tm.spbstu.ru/%D0%9C%D0%B0%D0%BB%D1%8B%D1%88%D0%B5%D0%B2%D0%B0_%D0%92%D0%B5%D1%80%D0%BE%D0%BD%D0%B8%D0%BA%D0%B0 Малышева В.Н.]
  
 
Группа 13632/1 Кафедра Теоретической механики.
 
Группа 13632/1 Кафедра Теоретической механики.
Строка 13: Строка 13:
 
{{#widget:Iframe |url=http://tm.spbstu.ru/htmlets/Demina_KV/zmeika.html |width=1100|height=800|border=0 }}
 
{{#widget:Iframe |url=http://tm.spbstu.ru/htmlets/Demina_KV/zmeika.html |width=1100|height=800|border=0 }}
 
== Код программы ==
 
== Код программы ==
<div class="mw-collapsible mw-collapsed">
+
window.addEventListener("load", main_code, false);
<syntaxhighlight lang="javascript" line start="1" enclose="div">
+
function main_code(){
window.addEventListener("load",main,false);
+
function main_code(){
+
var ctx = SnakeS.getContext("2d");
+
var ctx = SnakeS.getContext("2d");
var h = SnakeS.height;
+
var h = SnakeS.height;
var w = SnakeS.width;
+
var w = SnakeS.width;
var n = 45;
+
var n = 45;
var intervalID;
+
var intervalID;
var direction = "left";
+
var direction = "left";
var ms =200;
+
var ms =200;
var score = 0;
+
var score = 0;
var wCode = 87;
+
var wCode = 87;
var aCode = 65;
+
var aCode = 65;
var sCode = 83;
+
var sCode = 83;
var dCode = 68;
+
var dCode = 68;
var upCode = 38;
+
var upCode = 38;
var leftCode = 37;
+
var leftCode = 37;
var downCode = 40;
+
var downCode = 40;
var rightCode = 39;
+
var rightCode = 39;
var pause = false;
+
var pause = false;
function get_mouse_coords(e){  
+
var m = {};
+
function get_mouse_coords(e){  
var rect = SnakeS.getBoundingClientRect();
+
var m = {};
m.x = e.clientX - rect.left;
+
var rect = SnakeS.getBoundingClientRect();
m.y = e.clientY - rect.top;
+
m.x = e.clientX - rect.left;
return m;
+
m.y = e.clientY - rect.top;
}
+
return m;
SnakeS.onclick = function(e){
+
}
  var m = get_mouse_coords(e);
+
  console.log(m.x, m.y);
+
SnakeS.onclick = function(e){
  if ((m.x>(w/2-95))&&(m.x<(w/2+95))&&(m.y>(h/2+30))&&(m.y<(h/2+70))) {
+
var m = get_mouse_coords(e);
  console.log(1);
+
console.log(m.x, m.y);
  location.reload();
+
if ((m.x>(w/2-95))&&(m.x<(w/2+95))&&(m.y>(h/2+30))&&(m.y<(h/2+70))) {
  }
+
console.log(1);
}
+
location.reload();
var sl=1;
+
}
var nofood = false;
+
}
var nofoodno = false;
+
 
var x = w/n;
+
var sl=1;
var y = h/n;
+
var nofood = false;
console.log(x,y);
+
var nofoodno = false;
function box(){
+
  this.conteins = "empty";
+
var x = w/n;
}
+
var y = h/n;
function Snake(){
+
console.log(x,y);
  this.head = null;
+
  this.tail = null;
+
function box(){
  this.body = [];
+
this.conteins = "empty";
  this.length = 1;
+
}
}
+
var field = [];
+
function Snake(){
for (var i=0; i<n; i++) {
+
this.head = null;
  var m = [];
+
this.tail = null;
  for (var j=0; j<n; j++){
+
this.body = [];
  m.push(new box());
+
this.length = 1;
  }
+
}
  field.push(m);
+
}
+
var snake = new Snake();
+
var field = [];
function finish() {
+
for (var i=0; i<n; i++) {
  ctx.textAlign = 'center';
+
var m = [];
  ctx.font = '30px Georgia';
+
for (var j=0; j<n; j++){
  pause = true;
+
m.push(new box());
  console.error("Вы проиграли");
+
}
  clearInterval(intervalID);
+
field.push(m);
  ctx.fillStyle = 'rgb(180, 234, 255)';
+
}
  ctx.fillRect(0.25*w, 0.25*h, 0.5*w, 0.5*h);
+
var snake = new Snake();
  ctx.strokeStyle = 'black';
+
  ctx.strokeRect(0.25*w, 0.25*h, 0.5*w, 0.5*h);
+
  ctx.fillStyle = 'black';
+
  ctx.fillText('Вы проиграли!', w/2, h/2-40);
+
  ctx.fillText('Ваш счет: '+score, w/2, h/2);
+
function finish() {
  ctx.fillStyle = 'rgb(14, 151, 184)';
+
ctx.textAlign = 'center';
  ctx.fillRect(w/2-95, h/2+30, 190, 40);
+
ctx.font = '30px Georgia';
  ctx.strokeRect(w/2-95, h/2+30, 190, 40);
+
pause = true;
  ctx.fillStyle = 'black';
+
console.error("Вы проиграли");
  ctx.fillText('Сыграть еще', w/2, h/2+60);
+
clearInterval(intervalID);
  console.info('rtr');
+
ctx.fillStyle = 'rgb(180, 234, 255)';
}
+
ctx.fillRect(0.25*w, 0.25*h, 0.5*w, 0.5*h);
function CreateItem(item){
+
ctx.strokeStyle = 'black';
  var i=Math.round(Math.random()*(n - 1));
+
ctx.strokeRect(0.25*w, 0.25*h, 0.5*w, 0.5*h);
  var j=Math.round(Math.random()*(n - 1));
+
ctx.fillStyle = 'black';
  while (field [i][j].conteins != "empty"){
+
ctx.fillText('Вы проиграли!', w/2, h/2-40);
    var i=Math.round(Math.random()*(n - 1));
+
ctx.fillText('Ваш счет: '+score, w/2, h/2);
    var j=Math.round(Math.random()*(n - 1));
+
ctx.fillStyle = 'rgb(14, 151, 184)';
  }
+
ctx.fillRect(w/2-95, h/2+30, 190, 40);
  field [i][j].conteins = item;
+
ctx.strokeRect(w/2-95, h/2+30, 190, 40);
}
+
ctx.fillStyle = 'black';
function Init(){
+
ctx.fillText('Сыграть еще', w/2, h/2+60);
  var i=Math.round(Math.random()*(n - 1));
+
  var j=Math.round(Math.random()*(n - 1));
+
console.info('rtr');
  field [i][j].conteins = "food";
+
}
  var i=Math.round(Math.random()*(n - 1));
+
  var j=Math.round(Math.random()*(n - 1));
+
function CreateItem(item){
  while (field [i][j].conteins == "food"){
+
var i=Math.round(Math.random()*(n - 1));
    var i=Math.round(Math.random()*(n - 1));
+
var j=Math.round(Math.random()*(n - 1));
    var j=Math.round(Math.random()*(n - 1));
+
while (field [i][j].conteins != "empty"){
  }
+
var i=Math.round(Math.random()*(n - 1));
  field [i][j].conteins = "snake";
+
var j=Math.round(Math.random()*(n - 1));
  snake.head = {x: i, y: j};
+
}
  snake.tail = {x: i, y: j};
+
field [i][j].conteins = item;
  snake.body.push({x: i, y: j}) ;
+
  console.log(direction, snake.body, snake.head);
+
 
  CreateItem('nofood');
+
}
}
+
function Draw() {
+
function Init(){
  for (var i=0; i<n; i++) {
+
var i=Math.round(Math.random()*(n - 1));
  for (var j=0; j<n; j++){
+
var j=Math.round(Math.random()*(n - 1));
    if (field[i][j].conteins == "empty") {
+
field [i][j].conteins = "food";
    ctx.fillStyle = 'white';
+
    ctx.fillRect(x*i, y*j, x, y);
+
    }
+
var i=Math.round(Math.random()*(n - 1));
    if (field[i][j].conteins == "food") {
+
var j=Math.round(Math.random()*(n - 1));
    ctx.fillStyle = 'red';
+
while (field [i][j].conteins == "food"){
    ctx.fillRect(x*i, y*j, x, y);
+
var i=Math.round(Math.random()*(n - 1));
    ctx.strokeStyle = 'black';
+
var j=Math.round(Math.random()*(n - 1));
    ctx.strokeRect(x*i, y*j, x, y);
+
}
    }
+
field [i][j].conteins = "snake";
    if (field[i][j].conteins == "snake") {
+
snake.head = {x: i, y: j};
    ctx.fillStyle = 'green';
+
snake.tail = {x: i, y: j};
    ctx.fillRect(x*i, y*j, x, y);
+
snake.body.push({x: i, y: j}) ;
    ctx.strokeStyle = 'black';
+
console.log(direction, snake.body, snake.head);
    ctx.strokeRect(x*i, y*j, x, y);
+
    }
+
CreateItem('nofood');
    if (field[i][j].conteins == "nofood") {
+
}
    ctx.fillStyle = 'blue';
+
    ctx.fillRect(x*i, y*j, x, y);
+
    ctx.strokeStyle = 'black';
+
function Draw() {
    ctx.strokeRect(x*i, y*j, x, y);
+
for (var i=0; i<n; i++) {
    }
+
for (var j=0; j<n; j++){
    if (field[i][j].conteins == "nofoodno") {
+
if (field[i][j].conteins == "empty") {
    ctx.fillStyle = 'yellow';
+
ctx.fillStyle = 'white';
    ctx.fillRect(x*i, y*j, x, y);
+
ctx.fillRect(x*i, y*j, x, y);
    ctx.strokeStyle = 'black';
+
}
    ctx.strokeRect(x*i, y*j, x, y);
+
if (field[i][j].conteins == "food") {
    }
+
ctx.fillStyle = 'red';
  }
+
ctx.fillRect(x*i, y*j, x, y);
  }
+
ctx.strokeStyle = 'black';
  document.getElementById('scre').innerHTML = score;
+
ctx.strokeRect(x*i, y*j, x, y);
}
+
window.onkeydown = function(evt) {  
+
}
evt = evt || window.event;
+
if (field[i][j].conteins == "snake") {
var charCode = evt.keyCode || evt.which;
+
ctx.fillStyle = 'green';
console.log(charCode);  
+
ctx.fillRect(x*i, y*j, x, y);
if (((charCode == wCode)||(charCode == upCode)) && direction != "down") {
+
ctx.strokeStyle = 'black';
  direction = "up";
+
ctx.strokeRect(x*i, y*j, x, y);
}
+
}
if (((charCode == sCode)||(charCode == downCode)) && direction != "up") {
+
if (field[i][j].conteins == "nofood") {
  direction = "down";  
+
ctx.fillStyle = 'blue';
}
+
ctx.fillRect(x*i, y*j, x, y);
if (((charCode == aCode)||(charCode == leftCode)) && direction != "right") {
+
ctx.strokeStyle = 'black';
  direction = "left";
+
ctx.strokeRect(x*i, y*j, x, y);
}
+
}
if (((charCode == dCode)||(charCode == rightCode)) && direction != "left") {
+
if (field[i][j].conteins == "nofoodno") {
  direction = "right";
+
ctx.fillStyle = 'yellow';
}
+
ctx.fillRect(x*i, y*j, x, y);
}
+
ctx.strokeStyle = 'black';
function CheckLength() {
+
ctx.strokeRect(x*i, y*j, x, y);
  if ((score == 3) && (sl != 2)){
+
}
  sl = 2;
+
}
  ms = ms-100;
+
}
  clearInterval(intervalID);
+
document.getElementById('scre').innerHTML = score;
  intervalID = setInterval(control, ms);
+
}
  return ;
+
  }
+
window.onkeydown = function(evt) {  
  if ((score == 5 ) && (sl != 3)){
+
evt = evt || window.event;
  sl = 3;
+
var charCode = evt.keyCode || evt.which;
  ms = ms-50;
+
console.log(charCode);  
  clearInterval(intervalID);
+
if (((charCode == wCode)||(charCode == upCode)) && direction != "down") {
  intervalID = setInterval(control, ms);
+
direction = "up";
  }
+
}
+
}
function Calcul(){
+
if (((charCode == sCode)||(charCode == downCode)) && direction != "up") {
  var next  
+
direction = "down";  
  try {
+
}
  if (direction == "left") {
+
if (((charCode == aCode)||(charCode == leftCode)) && direction != "right") {
  next = {x: snake.head.x-1, y: snake.head.y}
+
direction = "left";
  }
+
}
  if (direction == "right") {
+
if (((charCode == dCode)||(charCode == rightCode)) && direction != "left") {
  next = {x: snake.head.x+1, y: snake.head.y}
+
direction = "right";
  }
+
}
  if (direction == "up") {
+
}
  next = {x: snake.head.x, y: snake.head.y-1}
+
  }
+
function CheckLength() {
  if (direction == "down" && snake.length == 1) {
+
if ((score == 3) && (sl != 2)){
  next = {x: snake.head.x, y: snake.head.y+1}
+
sl = 2;
  }
+
ms = ms-100;
  if (direction == "down" && snake.length > 1) {
+
clearInterval(intervalID);
  next = {x: snake.head.x, y: snake.head.y}
+
intervalID = setInterval(control, ms);
  }
+
return ;
  if (score > 5) {
+
}
  if (next.x<0) {
+
if ((score == 5 ) && (sl != 3)){
    next.x = n-1
+
sl = 3;
    console.log('TP')
+
ms = ms-50;
    }
+
clearInterval(intervalID);
  if (next.y<0) {
+
intervalID = setInterval(control, ms);
    next.y = n-1
+
}
    console.log('TP')
+
}
 +
 +
function Calcul(){
 +
var next  
 +
try {
 +
if (direction == "left") {
 +
next = {x: snake.head.x-1, y: snake.head.y}
 +
}
 +
if (direction == "right") {
 +
next = {x: snake.head.x+1, y: snake.head.y}
 +
}
 +
if (direction == "up") {
 +
next = {x: snake.head.x, y: snake.head.y-1}
 +
}
 +
if (direction == "down" && snake.length == 1) {
 +
next = {x: snake.head.x, y: snake.head.y+1}
 +
}
 +
if (direction == "down" && snake.length > 1) {
 +
next = {x: snake.head.x, y: snake.head.y}
 +
}
 +
 +
if (score > 5) {
 +
if (next.x<0) {
 +
next.x = n-1
 +
console.log('TP')
 +
}
 +
if (next.y<0) {
 +
next.y = n-1
 +
console.log('TP')
 +
}
 +
if (next.x>n-1) {
 +
next.x = 0
 +
console.log('TP')
 +
}
 +
if (next.y>n-1) {
 +
next.y = 0
 +
console.log('TP')
 +
}
 +
} else {
 +
if (next.x<0) {
 +
finish();
 +
return;
 +
}
 +
if (next.y<0) {
 +
finish();
 +
return;
 +
}
 +
if (next.x>n-1) {
 +
finish();
 +
return;
 +
}
 +
if (next.y>n-1) {
 +
finish();
 +
return;
 +
}
 +
}
 +
 +
if (field[next.x][next.y].conteins == "snake") {
 +
finish();
 +
return;
 +
}
 +
if (field[next.x][next.y].conteins == "food") {
 +
snake.body.push({x:next.x, y:next.y});
 +
snake.head = {x:next.x, y:next.y};
 +
field[next.x][next.y].conteins = "snake";
 +
CreateItem ('food');
 +
score++;
 +
 +
}
 +
if (field[next.x][next.y].conteins == "nofoodno") {
 +
snake.body.push({x:next.x, y:next.y});
 +
snake.head = {x:next.x, y:next.y};
 +
field[next.x][next.y].conteins = "snake";
 +
field[snake.body[0].x][snake.body[0].y].conteins = "empty";
 +
snake.body.shift();
 +
if(snake.body.length!=1)
 +
field[snake.body[0].x][snake.body[0].y].conteins = "empty";
 +
snake.body.shift();
 +
score++;
 +
nofoodno=false;
 +
 +
}
 +
 +
if (field[next.x][next.y].conteins == "nofood") {
 +
snake.body.push({x:next.x, y:next.y});
 +
snake.head = {x:next.x, y:next.y};
 +
field[next.x][next.y].conteins = "snake";
 +
field[snake.body[0].x][snake.body[0].y].conteins = "empty";
 +
snake.body.shift();
 +
score++;
 +
nofood=false;
 +
 +
}
 +
 +
 +
if (field[next.x][next.y].conteins == "empty") {
 +
snake.body.push({x:next.x, y:next.y});
 +
snake.head = {x:next.x, y:next.y};
 +
field[next.x][next.y].conteins = "snake";
 +
field[snake.body[0].x][snake.body[0].y].conteins = "empty";
 +
snake.body.shift();
 +
}
 +
} catch (err){
 +
console.error("Что то пошло не так; X=", next.x, "Y=", next.y);
 +
clearInterval(intervalID);
 +
}
 +
if (((score+1) % 5 == 0)&&(!nofood)){
 +
 +
CreateItem ('nofood');
 +
nofood=true;
 +
}
 +
if (((score+1) % 8 == 0)&&(!nofoodno)){
 +
 +
CreateItem ('nofoodno');
 +
nofoodno=true;
 +
}
 +
 +
}
 +
 +
function control (){
 +
if (!pause)
 +
Calcul ();
 +
if (!pause)
 +
Draw();
 +
CheckLength();
 +
}
 +
 +
 +
Init();
 +
Draw ();
 +
 +
intervalID = setInterval(control, ms);
 
      
 
      
  if (next.x>n-1) {
 
    next.x = 0
 
    console.log('TP')
 
    }
 
  if (next.y>n-1) {
 
    next.y = 0
 
    console.log('TP')
 
    }
 
  } else {
 
  if (next.x<0) {
 
    finish();
 
    return;
 
    }
 
  if (next.y<0) {
 
    finish();
 
    return;
 
    }
 
  if (next.x>n-1) {
 
    finish();
 
    return;
 
    }
 
  if (next.y>n-1) {
 
    finish();
 
    return;
 
    }
 
  }
 
  if (field[next.x][next.y].conteins == "snake") {
 
  finish();
 
  return;
 
  }
 
  if (field[next.x][next.y].conteins == "food") {
 
  snake.body.push({x:next.x, y:next.y});
 
  snake.head = {x:next.x, y:next.y};
 
  field[next.x][next.y].conteins = "snake";
 
  CreateItem ('food');
 
  score++;
 
  }
 
  if (field[next.x][next.y].conteins == "nofoodno") {
 
  snake.body.push({x:next.x, y:next.y});
 
  snake.head = {x:next.x, y:next.y};
 
  field[next.x][next.y].conteins = "snake";
 
  field[snake.body[0].x][snake.body[0].y].conteins = "empty";
 
  snake.body.shift();
 
  if(snake.body.length!=1)
 
    field[snake.body[0].x][snake.body[0].y].conteins = "empty";
 
    snake.body.shift();
 
  score++;
 
  nofoodno=false;
 
  }
 
  if (field[next.x][next.y].conteins == "nofood") {
 
  snake.body.push({x:next.x, y:next.y});
 
  snake.head = {x:next.x, y:next.y};
 
  field[next.x][next.y].conteins = "snake";
 
  field[snake.body[0].x][snake.body[0].y].conteins = "empty";
 
  snake.body.shift();
 
  score++;
 
  nofood=false;
 
  }
 
  if (field[next.x][next.y].conteins == "empty") {
 
  snake.body.push({x:next.x, y:next.y});
 
  snake.head = {x:next.x, y:next.y};
 
  field[next.x][next.y].conteins = "snake";
 
  field[snake.body[0].x][snake.body[0].y].conteins = "empty";
 
  snake.body.shift();
 
  }
 
  } catch (err){
 
  console.error("Что то пошло не так; X=", next.x, "Y=", next.y);
 
  clearInterval(intervalID);
 
  }
 
  if (((score+1) % 5 == 0)&&(!nofood)){
 
  CreateItem ('nofood');
 
  nofood=true;
 
  }
 
  if (((score+1) % 8 == 0)&&(!nofoodno)){
 
  CreateItem ('nofoodno');
 
  nofoodno=true;
 
  }
 
}
 
function control (){
 
  if (!pause)
 
  Calcul ();
 
  if (!pause)
 
  Draw();
 
  CheckLength();
 
}
 
Init();
 
Draw ();
 
intervalID = setInterval(control, ms);
 
 
}
 
}
</syntaxhighlight>
 
</div>
 
Вам запрещено изменять защиту статьи. Edit Создать редактором

Обратите внимание, что все добавления и изменения текста статьи рассматриваются как выпущенные на условиях лицензии Public Domain (см. Department of Theoretical and Applied Mechanics:Авторские права). Если вы не хотите, чтобы ваши тексты свободно распространялись и редактировались любым желающим, не помещайте их сюда.
Вы также подтверждаете, что являетесь автором вносимых дополнений или скопировали их из источника, допускающего свободное распространение и изменение своего содержимого.
НЕ РАЗМЕЩАЙТЕ БЕЗ РАЗРЕШЕНИЯ МАТЕРИАЛЫ, ОХРАНЯЕМЫЕ АВТОРСКИМ ПРАВОМ!

To protect the wiki against automated edit spam, we kindly ask you to solve the following CAPTCHA:

Отменить | Справка по редактированию  (в новом окне)