Mostrando entradas con la etiqueta picturebox. Mostrar todas las entradas
Mostrando entradas con la etiqueta picturebox. Mostrar todas las entradas

sábado, 27 de agosto de 2016

Como hacer un juego de Snake en C# (Windows Forms)


Para ver en youtube clic aquí
(No olvides suscribirte)


Juego de snake

   Este juego fue lanzado a mediados de lo años 70, a diferencia de lo que muchos creen no fue desarrollado por la Nokia, pero gracias a esta última adquirió una popularidad masiva debido a que venia pre-instalado en los teléfonos de esta marca.

Archivos del Video tutorial

  Nota: Todos los enlaces están patrocinados por Adfly luego de hacer clic esperas unos segundos y haces clic en "Saltar publicidad", debería llevarte directamente al archivo para su descarga, si no es así comunícate inmediatamente conmigo a través de un comentario

Imágenes

Ejemplo de Snake en WPF (Windows Presentation Foundation) proyecto completo Visual Studio

   Este último ejemplo es para que compares las diferencias con Windows Forms, no son muchas, estas solo son referentes a la interfaz gráfica, suscríbete a mi canal para ver más tutoriales como este, pronto publicaré el mismo tutorial pero en WPF

Código fuente completo (Windows Forms)

Form1.cs


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace snake1
{
    public partial class Form1 : Form
    {
        Graphics juego;
        Cola cabeza;
        Comida comida;
        int espacio;
        int xdir = 0,ydir = 0;
        int puntaje = 0;
        Boolean ejex = true, ejey = true;
        public Form1()
        {
            espacio = 10;
            InitializeComponent();
            juego = canvas.CreateGraphics();
            cabeza = new Cola(10, 10);
            comida = new Comida();
        }
        public void findeJuego()
        {
            xdir = 0;
            ydir = 0;
            puntaje = 0;
            puntos.Text = "0";
            ejex = true;
            ejey = true;
            cabeza = new Cola(10, 10);
            comida = new Comida();
            MessageBox.Show("Perdiste");
        }
        public void choqueCuerpo()
        {
            Cola temp;
            try
            {
                temp = cabeza.verSiguiente().verSiguiente();
            } catch(Exception err)
            {
                temp = null;
            }
            while(temp != null)
            {
                if (cabeza.interseccion(temp))
                {
                    findeJuego();
                } else
                {
                    temp = temp.verSiguiente();
                }
            }
        }

        public void choquePared()
        {
            if(cabeza.getX() < 0 || cabeza.getX() > 760 || cabeza.getY() < 0 || cabeza.getY() > 360)
            {
                findeJuego();
            }
        }

        public void dibujar()
        {
            juego.Clear(Color.White);
            cabeza.dibujar(juego);
            comida.dibujar(juego);
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (ejex)
            {
                if(e.KeyCode == Keys.Up)
                {
                    ydir = -espacio;
                    xdir = 0;
                    ejex = false;
                    ejey = true;
                }
                if (e.KeyCode == Keys.Down)
                {
                    ydir = espacio;
                    xdir = 0;
                    ejex = false;
                    ejey = true;
                }
            }
            if (ejey)
            {
                if (e.KeyCode == Keys.Right)
                {
                    ydir = 0;
                    xdir = espacio;
                    ejex = true;
                    ejey = false;
                }
                if (e.KeyCode == Keys.Left)
                {
                    ydir = 0;
                    xdir = -espacio;
                    ejex = true;
                    ejey = false;
                }
            }
        }

        public void movimiento()
        {
            cabeza.setxy(cabeza.getX() + xdir, cabeza.getY() + ydir);
        }

        private void bucle_Tick(object sender, EventArgs e)
        {
            dibujar();
            movimiento();
            choqueCuerpo();
            choquePared();
            if (cabeza.interseccion(comida))
            {
                comida.colocar();
                cabeza.meter();
                puntos.Text = (puntaje++).ToString();
            }
        }
    }
}

Cola.cs

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace snake1
{
    class Cola : objeto
    {
        Cola siguiente;
        public Cola(int x, int y)
        {
            this.x = x;
            this.y = y;
            siguiente = null;
        }
        public void dibujar(Graphics g)
        {
            if(siguiente != null)
            {
                siguiente.dibujar(g);
            }
            g.FillRectangle(new SolidBrush(Color.Blue), this.x, this.y, this.espacio, this.espacio);
        }
        public void setxy(int x, int y)
        {
            if(siguiente != null)
            {
                siguiente.setxy(this.x, this.y);
            }
            this.x = x;
            this.y = y;
        }
        public void meter()
        {
            if(siguiente == null)
            {
                siguiente = new Cola(this.x, this.y);
            } else
            {
                siguiente.meter();
            }
        }
        public int getX()
        {
            return this.x;
        }
        public int getY()
        {
            return this.y;
        }
        public Cola verSiguiente()
        {
            return siguiente;
        }
    }
}

objeto.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace snake1
{
    class objeto
    {
        protected int x, y, espacio;
        public objeto()
        {
            espacio = 10;
        }
        public Boolean interseccion(objeto o)
        {
            int difx = Math.Abs(this.x - o.x);
            int dify = Math.Abs(this.y - o.y);
            if(difx >= 0 && difx < espacio && dify >= 0 && dify < espacio)
            {
                return true;
            } else
            {
                return false;
            }
        }
    }
}

Comida.cs

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace snake1
{
    class Comida : objeto
    {

        public Comida()
        {
            this.x = generar(77);
            this.y = generar(37);
        }
        public void dibujar(Graphics g)
        {
            g.FillRectangle(new SolidBrush(Color.Red), this.x, this.y, this.espacio, this.espacio);
        }
        public void colocar()
        {
            this.x = generar(77);
            this.y = generar(37);
        }
        public int generar(int n)
        {
            Random random = new Random();
            int num = random.Next(0, n) * 10;
            return num;
        }
    }
}