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

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

Внимание! Вы не авторизовались на сайте. Ваш 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 Кафедра Теоретической механики.
Строка 14: Строка 14:
 
== Код программы ==
 
== Код программы ==
 
<div class="mw-collapsible mw-collapsed">
 
<div class="mw-collapsible mw-collapsed">
<syntaxhighlight lang="javascript" line start="1" enclose="div">
+
<syntaxhighlight lang=javascript>
window.addEventListener("load",main,false);
+
window.addEventListener("load", main_code, false);
function main_code(){
+
function main_code(){
 
  var ctx = SnakeS.getContext("2d");
 
  var ctx = SnakeS.getContext("2d");
 
  var h = SnakeS.height;
 
  var h = SnakeS.height;
Строка 34: Строка 34:
 
  var rightCode = 39;
 
  var rightCode = 39;
 
  var pause = false;
 
  var pause = false;
function get_mouse_coords(e){  
+
function get_mouse_coords(e){  
var m = {};
+
var m = {};
var rect = SnakeS.getBoundingClientRect();
+
var rect = SnakeS.getBoundingClientRect();
m.x = e.clientX - rect.left;
+
m.x = e.clientX - rect.left;
m.y = e.clientY - rect.top;
+
m.y = e.clientY - rect.top;
return m;
+
return m;
}
+
}
SnakeS.onclick = function(e){
+
SnakeS.onclick = function(e){
  var m = get_mouse_coords(e);
+
var m = get_mouse_coords(e);
  console.log(m.x, m.y);
+
console.log(m.x, m.y);
  if ((m.x>(w/2-95))&&(m.x<(w/2+95))&&(m.y>(h/2+30))&&(m.y<(h/2+70))) {
+
if ((m.x>(w/2-95))&&(m.x<(w/2+95))&&(m.y>(h/2+30))&&(m.y<(h/2+70))) {
  console.log(1);
+
console.log(1);
  location.reload();
+
location.reload();
  }
+
}
}
+
}
 
  var sl=1;
 
  var sl=1;
 
  var nofood = false;
 
  var nofood = false;
Строка 55: Строка 55:
 
  var y = h/n;
 
  var y = h/n;
 
  console.log(x,y);
 
  console.log(x,y);
function box(){
+
function box(){
  this.conteins = "empty";
+
this.conteins = "empty";
}
+
}
function Snake(){
+
  this.head = null;
+
function Snake(){
  this.tail = null;
+
this.head = null;
  this.body = [];
+
this.tail = null;
  this.length = 1;
+
this.body = [];
}
+
this.length = 1;
var field = [];
+
}
for (var i=0; i<n; i++) {
+
var field = [];
  var m = [];
+
for (var i=0; i<n; i++) {
  for (var j=0; j<n; j++){
+
var m = [];
  m.push(new box());
+
for (var j=0; j<n; j++){
  }
+
m.push(new box());
  field.push(m);
+
}
}
+
field.push(m);
var snake = new Snake();
+
}
function finish() {
+
var snake = new Snake();
  ctx.textAlign = 'center';
+
function finish() {
  ctx.font = '30px Georgia';
+
ctx.textAlign = 'center';
  pause = true;
+
ctx.font = '30px Georgia';
  console.error("Вы проиграли");
+
pause = true;
  clearInterval(intervalID);
+
console.error("Вы проиграли");
  ctx.fillStyle = 'rgb(180, 234, 255)';
+
clearInterval(intervalID);
  ctx.fillRect(0.25*w, 0.25*h, 0.5*w, 0.5*h);
+
ctx.fillStyle = 'rgb(180, 234, 255)';
  ctx.strokeStyle = 'black';
+
ctx.fillRect(0.25*w, 0.25*h, 0.5*w, 0.5*h);
  ctx.strokeRect(0.25*w, 0.25*h, 0.5*w, 0.5*h);
+
ctx.strokeStyle = 'black';
  ctx.fillStyle = 'black';
+
ctx.strokeRect(0.25*w, 0.25*h, 0.5*w, 0.5*h);
  ctx.fillText('Вы проиграли!', w/2, h/2-40);
+
ctx.fillStyle = 'black';
  ctx.fillText('Ваш счет: '+score, w/2, h/2);
+
ctx.fillText('Вы проиграли!', w/2, h/2-40);
  ctx.fillStyle = 'rgb(14, 151, 184)';
+
ctx.fillText('Ваш счет: '+score, w/2, h/2);
  ctx.fillRect(w/2-95, h/2+30, 190, 40);
+
ctx.fillStyle = 'rgb(14, 151, 184)';
  ctx.strokeRect(w/2-95, h/2+30, 190, 40);
+
ctx.fillRect(w/2-95, h/2+30, 190, 40);
  ctx.fillStyle = 'black';
+
ctx.strokeRect(w/2-95, h/2+30, 190, 40);
  ctx.fillText('Сыграть еще', w/2, h/2+60);
+
ctx.fillStyle = 'black';
  console.info('rtr');
+
ctx.fillText('Сыграть еще', w/2, h/2+60);
}
+
function CreateItem(item){
+
console.info('rtr');
  var i=Math.round(Math.random()*(n - 1));
+
}
  var j=Math.round(Math.random()*(n - 1));
+
function CreateItem(item){
  while (field [i][j].conteins != "empty"){
+
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 = item;
+
var j=Math.round(Math.random()*(n - 1));
}
+
}
function Init(){
+
field [i][j].conteins = item;
  var i=Math.round(Math.random()*(n - 1));
+
}
  var j=Math.round(Math.random()*(n - 1));
+
function Init(){
  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));
+
field [i][j].conteins = "food";
  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 == "food"){
  }
+
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 = "snake";
  snake.body.push({x: i, y: j}) ;
+
snake.head = {x: i, y: j};
  console.log(direction, snake.body, snake.head);
+
snake.tail = {x: i, y: j};
  CreateItem('nofood');
+
snake.body.push({x: i, y: j}) ;
}
+
console.log(direction, snake.body, snake.head);
function Draw() {
+
  for (var i=0; i<n; i++) {
+
CreateItem('nofood');
  for (var j=0; j<n; j++){
+
}
    if (field[i][j].conteins == "empty") {
+
function Draw() {
    ctx.fillStyle = 'white';
+
for (var i=0; i<n; i++) {
    ctx.fillRect(x*i, y*j, x, y);
+
for (var j=0; j<n; j++){
    }
+
if (field[i][j].conteins == "empty") {
    if (field[i][j].conteins == "food") {
+
ctx.fillStyle = 'white';
    ctx.fillStyle = 'red';
+
ctx.fillRect(x*i, y*j, x, y);
    ctx.fillRect(x*i, y*j, x, y);
+
}
    ctx.strokeStyle = 'black';
+
if (field[i][j].conteins == "food") {
    ctx.strokeRect(x*i, y*j, x, y);
+
ctx.fillStyle = 'red';
    }
+
ctx.fillRect(x*i, y*j, x, y);
    if (field[i][j].conteins == "snake") {
+
ctx.strokeStyle = 'black';
    ctx.fillStyle = 'green';
+
ctx.strokeRect(x*i, y*j, x, y);
    ctx.fillRect(x*i, y*j, x, y);
+
}
    ctx.strokeStyle = 'black';
+
if (field[i][j].conteins == "snake") {
    ctx.strokeRect(x*i, y*j, x, y);
+
ctx.fillStyle = 'green';
    }
+
ctx.fillRect(x*i, y*j, x, y);
    if (field[i][j].conteins == "nofood") {
+
ctx.strokeStyle = 'black';
    ctx.fillStyle = 'blue';
+
ctx.strokeRect(x*i, y*j, x, y);
    ctx.fillRect(x*i, y*j, x, y);
+
}
    ctx.strokeStyle = 'black';
+
if (field[i][j].conteins == "nofood") {
    ctx.strokeRect(x*i, y*j, x, y);
+
ctx.fillStyle = 'blue';
    }
+
ctx.fillRect(x*i, y*j, x, y);
    if (field[i][j].conteins == "nofoodno") {
+
ctx.strokeStyle = 'black';
    ctx.fillStyle = 'yellow';
+
ctx.strokeRect(x*i, y*j, x, y);
    ctx.fillRect(x*i, y*j, x, y);
+
}
    ctx.strokeStyle = 'black';
+
if (field[i][j].conteins == "nofoodno") {
    ctx.strokeRect(x*i, y*j, x, y);
+
ctx.fillStyle = 'yellow';
    }
+
ctx.fillRect(x*i, y*j, x, y);
  }
+
ctx.strokeStyle = 'black';
  }
+
ctx.strokeRect(x*i, y*j, x, y);
  document.getElementById('scre').innerHTML = score;
+
}
}
+
}
window.onkeydown = function(evt) {  
+
}
evt = evt || window.event;
+
document.getElementById('scre').innerHTML = score;
var charCode = evt.keyCode || evt.which;
+
}
console.log(charCode);  
+
window.onkeydown = function(evt) {  
if (((charCode == wCode)||(charCode == upCode)) && direction != "down") {
+
evt = evt || window.event;
  direction = "up";
+
var charCode = evt.keyCode || evt.which;
}
+
console.log(charCode);  
if (((charCode == sCode)||(charCode == downCode)) && direction != "up") {
+
if (((charCode == wCode)||(charCode == upCode)) && direction != "down") {
  direction = "down";  
+
direction = "up";
}
+
}
if (((charCode == aCode)||(charCode == leftCode)) && direction != "right") {
+
if (((charCode == sCode)||(charCode == downCode)) && direction != "up") {
  direction = "left";
+
direction = "down";  
}
+
}
if (((charCode == dCode)||(charCode == rightCode)) && direction != "left") {
+
if (((charCode == aCode)||(charCode == leftCode)) && direction != "right") {
  direction = "right";
+
direction = "left";
}
+
}
}
+
if (((charCode == dCode)||(charCode == rightCode)) && direction != "left") {
function CheckLength() {
+
direction = "right";
  if ((score == 3) && (sl != 2)){
+
}
  sl = 2;
+
}
  ms = ms-100;
+
function CheckLength() {
  clearInterval(intervalID);
+
if ((score == 3) && (sl != 2)){
  intervalID = setInterval(control, ms);
+
sl = 2;
  return ;
+
ms = ms-100;
  }
+
clearInterval(intervalID);
  if ((score == 5 ) && (sl != 3)){
+
intervalID = setInterval(control, ms);
  sl = 3;
+
return ;
  ms = ms-50;
+
}
  clearInterval(intervalID);
+
if ((score == 5 ) && (sl != 3)){
  intervalID = setInterval(control, ms);
+
sl = 3;
  }
+
ms = ms-50;
}
+
clearInterval(intervalID);
function Calcul(){
+
intervalID = setInterval(control, ms);
  var next  
+
}
  try {
+
}
  if (direction == "left") {
+
function Calcul(){
  next = {x: snake.head.x-1, y: snake.head.y}
+
var next  
  }
+
try {
  if (direction == "right") {
+
if (direction == "left") {
  next = {x: snake.head.x+1, y: snake.head.y}
+
next = {x: snake.head.x-1, y: snake.head.y}
  }
+
}
  if (direction == "up") {
+
if (direction == "right") {
  next = {x: snake.head.x, y: snake.head.y-1}
+
next = {x: snake.head.x+1, y: snake.head.y}
  }
+
}
  if (direction == "down" && snake.length == 1) {
+
if (direction == "up") {
  next = {x: snake.head.x, y: snake.head.y+1}
+
next = {x: snake.head.x, y: snake.head.y-1}
  }
+
}
  if (direction == "down" && snake.length > 1) {
+
if (direction == "down" && snake.length == 1) {
  next = {x: snake.head.x, y: snake.head.y}
+
next = {x: snake.head.x, y: snake.head.y+1}
  }
+
}
  if (score > 5) {
+
if (direction == "down" && snake.length > 1) {
  if (next.x<0) {
+
next = {x: snake.head.x, y: snake.head.y}
    next.x = n-1
+
}
    console.log('TP')
+
if (score > 5) {
    }
+
if (next.x<0) {
  if (next.y<0) {
+
next.x = n-1
    next.y = n-1
+
console.log('TP')
    console.log('TP')
+
}
   
+
if (next.y<0) {
  if (next.x>n-1) {
+
next.y = n-1
    next.x = 0
+
console.log('TP')
    console.log('TP')
+
}
    }
+
if (next.x>n-1) {
  if (next.y>n-1) {
+
next.x = 0
    next.y = 0
+
console.log('TP')
    console.log('TP')
+
}
    }
+
if (next.y>n-1) {
  } else {
+
next.y = 0
  if (next.x<0) {
+
console.log('TP')
    finish();
+
}
    return;
+
} else {
    }
+
if (next.x<0) {
  if (next.y<0) {
+
finish();
    finish();
+
return;
    return;
+
}
    }
+
if (next.y<0) {
  if (next.x>n-1) {
+
finish();
    finish();
+
return;
    return;
+
}
    }
+
if (next.x>n-1) {
  if (next.y>n-1) {
+
finish();
    finish();
+
return;
    return;
+
}
    }
+
if (next.y>n-1) {
  }
+
finish();
  if (field[next.x][next.y].conteins == "snake") {
+
return;
  finish();
+
}
  return;
+
}
  }
+
  if (field[next.x][next.y].conteins == "food") {
+
if (field[next.x][next.y].conteins == "snake") {
  snake.body.push({x:next.x, y:next.y});
+
finish();
  snake.head = {x:next.x, y:next.y};
+
return;
  field[next.x][next.y].conteins = "snake";
+
}
  CreateItem ('food');
+
if (field[next.x][next.y].conteins == "food") {
  score++;
+
snake.body.push({x:next.x, y:next.y});
  }
+
snake.head = {x:next.x, y:next.y};
  if (field[next.x][next.y].conteins == "nofoodno") {
+
field[next.x][next.y].conteins = "snake";
  snake.body.push({x:next.x, y:next.y});
+
CreateItem ('food');
  snake.head = {x:next.x, y:next.y};
+
score++;
  field[next.x][next.y].conteins = "snake";
+
}
  field[snake.body[0].x][snake.body[0].y].conteins = "empty";
+
if (field[next.x][next.y].conteins == "nofoodno") {
  snake.body.shift();
+
snake.body.push({x:next.x, y:next.y});
  if(snake.body.length!=1)
+
snake.head = {x:next.x, y:next.y};
    field[snake.body[0].x][snake.body[0].y].conteins = "empty";
+
field[next.x][next.y].conteins = "snake";
    snake.body.shift();
+
field[snake.body[0].x][snake.body[0].y].conteins = "empty";
  score++;
+
snake.body.shift();
  nofoodno=false;
+
if(snake.body.length!=1)
  }
+
field[snake.body[0].x][snake.body[0].y].conteins = "empty";
  if (field[next.x][next.y].conteins == "nofood") {
+
snake.body.shift();
  snake.body.push({x:next.x, y:next.y});
+
score++;
  snake.head = {x:next.x, y:next.y};
+
nofoodno=false;
  field[next.x][next.y].conteins = "snake";
+
}
  field[snake.body[0].x][snake.body[0].y].conteins = "empty";
+
if (field[next.x][next.y].conteins == "nofood") {
  snake.body.shift();
+
snake.body.push({x:next.x, y:next.y});
  score++;
+
snake.head = {x:next.x, y:next.y};
  nofood=false;
+
field[next.x][next.y].conteins = "snake";
  }
+
field[snake.body[0].x][snake.body[0].y].conteins = "empty";
  if (field[next.x][next.y].conteins == "empty") {
+
snake.body.shift();
  snake.body.push({x:next.x, y:next.y});
+
score++;
  snake.head = {x:next.x, y:next.y};
+
nofood=false;
  field[next.x][next.y].conteins = "snake";
+
}
  field[snake.body[0].x][snake.body[0].y].conteins = "empty";
+
if (field[next.x][next.y].conteins == "empty") {
  snake.body.shift();
+
snake.body.push({x:next.x, y:next.y});
  }
+
snake.head = {x:next.x, y:next.y};
  } catch (err){
+
field[next.x][next.y].conteins = "snake";
  console.error("Что то пошло не так; X=", next.x, "Y=", next.y);
+
field[snake.body[0].x][snake.body[0].y].conteins = "empty";
  clearInterval(intervalID);
+
snake.body.shift();
  }
+
}
  if (((score+1) % 5 == 0)&&(!nofood)){
+
} catch (err){
  CreateItem ('nofood');
+
console.error("Что то пошло не так; X=", next.x, "Y=", next.y);
  nofood=true;
+
clearInterval(intervalID);
  }
+
}
  if (((score+1) % 8 == 0)&&(!nofoodno)){
+
if (((score+1) % 5 == 0)&&(!nofood)){
  CreateItem ('nofoodno');
+
CreateItem ('nofood');
  nofoodno=true;
+
nofood=true;
  }
+
}
}
+
if (((score+1) % 8 == 0)&&(!nofoodno)){
function control (){
+
CreateItem ('nofoodno');
  if (!pause)
+
nofoodno=true;
  Calcul ();
+
}
  if (!pause)
+
}
  Draw();
+
  CheckLength();
+
function control (){
}
+
if (!pause)
Init();
+
Calcul ();
Draw ();
+
if (!pause)
intervalID = setInterval(control, ms);
+
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:

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