¿Quieres reaccionar a este mensaje? Regístrate en el foro con unos pocos clics o inicia sesión para continuar.

[PC] Juego del snake, hecho por mi :P

+2
Franshuale
Kronos
6 participantes

 :: Ocio :: Videojuegos

Ir abajo

[PC] Juego del snake, hecho por mi :P Empty [PC] Juego del snake, hecho por mi :P

Mensaje por Kronos Vie Ene 16, 2009 4:59 pm

Pues nada, que pense en hacer un juego desde 0 con lo que habia aprendido de opengl, y c++, y este es el resultado. Es el juego del Snake de toda la vida... Si lo probais decidme vuestra opinion Very Happy . A ver si se anima alguno ha hacer algo jejej. Saludos

http://www.megaupload.com/?d=UYSNM2FI

[PC] Juego del snake, hecho por mi :P Juegofv8
[PC] Juego del snake, hecho por mi :P W680


Última edición por Kronos el Mar Feb 03, 2009 10:08 pm, editado 6 veces
Kronos
Kronos
Erudito

Masculino
Cantidad de envíos : 483
Edad : 34
Localización : Aulario B3
Fecha de inscripción : 09/10/2008

Volver arriba Ir abajo

[PC] Juego del snake, hecho por mi :P Empty Re: [PC] Juego del snake, hecho por mi :P

Mensaje por Franshuale Sáb Ene 17, 2009 11:15 pm

[Hoygan]Hoyga, tene qe pagar los derexoh de ahutor!!! ihoputa! xD[/Hoygan]

Se sale el juego, para que luego digan que OpenGL solo sirve para hacer teteras y lineas Very Happy
Franshuale
Franshuale
Erudito

Masculino
Cantidad de envíos : 321
Edad : 34
Localización : Córdoba
Fecha de inscripción : 09/10/2008

Volver arriba Ir abajo

[PC] Juego del snake, hecho por mi :P Empty Re: [PC] Juego del snake, hecho por mi :P

Mensaje por Kronos Dom Ene 18, 2009 12:29 pm

jejeje, lo mas wapo es cuando se rie nico cuando te estrellas XD
Kronos
Kronos
Erudito

Masculino
Cantidad de envíos : 483
Edad : 34
Localización : Aulario B3
Fecha de inscripción : 09/10/2008

Volver arriba Ir abajo

[PC] Juego del snake, hecho por mi :P Empty Re: [PC] Juego del snake, hecho por mi :P

Mensaje por Admin Dom Ene 18, 2009 4:10 pm

A mi no se me oye al nico riendose. Crying or Very sad

Admin
Admin

Masculino
Cantidad de envíos : 568
Edad : 35
Fecha de inscripción : 08/10/2008

https://sistematicos.forosactivos.net

Volver arriba Ir abajo

[PC] Juego del snake, hecho por mi :P Empty Re: [PC] Juego del snake, hecho por mi :P

Mensaje por Kronos Dom Ene 18, 2009 7:48 pm

Es cuando t estrellas en la pared, pero debes dejar la carpeta tal y como esta, para que "encuentre" el archivo de sonido.
Kronos
Kronos
Erudito

Masculino
Cantidad de envíos : 483
Edad : 34
Localización : Aulario B3
Fecha de inscripción : 09/10/2008

Volver arriba Ir abajo

[PC] Juego del snake, hecho por mi :P Empty Re: [PC] Juego del snake, hecho por mi :P

Mensaje por Admin Dom Ene 18, 2009 11:42 pm

Ya, ahora si. Laughing

Tio si posteas el codigo eres mi Fucking Idolo!!

Admin
Admin

Masculino
Cantidad de envíos : 568
Edad : 35
Fecha de inscripción : 08/10/2008

https://sistematicos.forosactivos.net

Volver arriba Ir abajo

[PC] Juego del snake, hecho por mi :P Empty Re: [PC] Juego del snake, hecho por mi :P

Mensaje por Finthalas Lun Ene 19, 2009 1:07 pm

Muy bueno, horas de entretenimiento gratuito. Enhorabuena y gracias.
Finthalas
Finthalas
Iniciado

Masculino
Cantidad de envíos : 6
Edad : 37
Localización : Out of the Silent Planet
Empleo /Ocio : Lighting teh Multiverse
Fecha de inscripción : 21/11/2008

Volver arriba Ir abajo

[PC] Juego del snake, hecho por mi :P Empty Re: [PC] Juego del snake, hecho por mi :P

Mensaje por Kronos Lun Ene 19, 2009 10:37 pm

Gracias por probarlo, me alegro de que os guste jeje, aqui os dejo la nueva version.
-Le he puesto un boton para reiniciar la partida (r)
-Le he puesto unas paredes transportadoras (la parte que esta en amarillo).
-En el boton 's' le he puesto una sorpresilla jeje
-Tambien le he cambiado algunas frases que antes salian por consola y ahora lo hace en la ventana de juego.
-Incluye el archivo de las librerias (puesto que no todos tenemos instalado el GLUT)

Espero que os guste la nueva version jejej.

http://www.megaupload.com/?d=QDMKXL1I
Kronos
Kronos
Erudito

Masculino
Cantidad de envíos : 483
Edad : 34
Localización : Aulario B3
Fecha de inscripción : 09/10/2008

Volver arriba Ir abajo

[PC] Juego del snake, hecho por mi :P Empty Re: [PC] Juego del snake, hecho por mi :P

Mensaje por Amonshy Miér Ene 21, 2009 6:23 pm

El juego tiene un bug Javi, mañana te lo explico en clase.

Te dejo una captura:

[PC] Juego del snake, hecho por mi :P Dibujoem8

Despues de un buen rato te dices que pierdes pero mira todas las veces que cruze la serpiente.

Un saludo.
Amonshy
Amonshy
Maestro

Masculino
Cantidad de envíos : 260
Edad : 34
Localización : Córdoba
Empleo /Ocio : Estudiante
Fecha de inscripción : 09/10/2008

Volver arriba Ir abajo

[PC] Juego del snake, hecho por mi :P Empty Re: [PC] Juego del snake, hecho por mi :P

Mensaje por Kronos Jue Ene 22, 2009 10:44 am

No es un bug, si pulsas la "s" , se hace grande , pero no se come!!, hasta que hayas comido alguna manzana. Lo puse asi precisamente para poderte hacer muy grande, pero tan pronto comas alguna manzana, ZASCA!!! XD.
Saludos
Kronos
Kronos
Erudito

Masculino
Cantidad de envíos : 483
Edad : 34
Localización : Aulario B3
Fecha de inscripción : 09/10/2008

Volver arriba Ir abajo

[PC] Juego del snake, hecho por mi :P Empty Re: [PC] Juego del snake, hecho por mi :P

Mensaje por ReyLith Jue Ene 22, 2009 11:28 am

Deberías ponerle varios niveles (no solo de dificultad) sino que al llegar a un determinado nivel de puntos saltase a otra pantalla que tuviese obstáculos. He oido que el generador de colisiones te lo encuentras hecho y demás. Así que no creo que haya mucho problema en hacerlo.... Se podría empezar con algo simple... una barra en medio, después dos, y así sucesivamente Very Happy. Animo!!
ReyLith
ReyLith
Erudito

Masculino
Cantidad de envíos : 382
Edad : 34
Localización : La concha de la Lora
Fecha de inscripción : 09/10/2008

Volver arriba Ir abajo

[PC] Juego del snake, hecho por mi :P Empty Re: [PC] Juego del snake, hecho por mi :P

Mensaje por Kronos Jue Ene 22, 2009 10:06 pm

Como diria Manu en mitad de una clase "mmm. interesante" XD, lo malo es que el "proyecto" deberá esperar despues de los examenes, en principio solo iba a hacer un punto que se moviera (algo parecido a un juego), y al final me he picado y cada dia le añado algo nuevo, y hasta de vez en cuando me exo una partida, mientras se me descarga algo, o toy aburrido jejej.
Gracias por probarlo Wink
Kronos
Kronos
Erudito

Masculino
Cantidad de envíos : 483
Edad : 34
Localización : Aulario B3
Fecha de inscripción : 09/10/2008

Volver arriba Ir abajo

[PC] Juego del snake, hecho por mi :P Empty Re: [PC] Juego del snake, hecho por mi :P

Mensaje por Amonshy Dom Ene 25, 2009 6:47 pm

Aquí os dejo una prueba del poder de OpenGl....

http://www.megaupload.com/?d=C8KX17R8

Un saludo.
Amonshy
Amonshy
Maestro

Masculino
Cantidad de envíos : 260
Edad : 34
Localización : Córdoba
Empleo /Ocio : Estudiante
Fecha de inscripción : 09/10/2008

Volver arriba Ir abajo

[PC] Juego del snake, hecho por mi :P Empty Re: [PC] Juego del snake, hecho por mi :P

Mensaje por Admin Dom Ene 25, 2009 8:57 pm

Pues a mi me da error y no se me incia.

CGfxOpenGL class failed to inicializated.

Admin
Admin

Masculino
Cantidad de envíos : 568
Edad : 35
Fecha de inscripción : 08/10/2008

https://sistematicos.forosactivos.net

Volver arriba Ir abajo

[PC] Juego del snake, hecho por mi :P Empty Re: [PC] Juego del snake, hecho por mi :P

Mensaje por ReyLith Lun Ene 26, 2009 1:09 am

Me ocurre lo mismo que al Agente Cubata XD
ReyLith
ReyLith
Erudito

Masculino
Cantidad de envíos : 382
Edad : 34
Localización : La concha de la Lora
Fecha de inscripción : 09/10/2008

Volver arriba Ir abajo

[PC] Juego del snake, hecho por mi :P Empty Re: [PC] Juego del snake, hecho por mi :P

Mensaje por Amonshy Lun Ene 26, 2009 1:22 am

Bueno hasta que arregle el enlace aquí os dejo otro, jajaja.

http://www.megaupload.com/?d=QVYQ2MCQ

Un saludo.
Amonshy
Amonshy
Maestro

Masculino
Cantidad de envíos : 260
Edad : 34
Localización : Córdoba
Empleo /Ocio : Estudiante
Fecha de inscripción : 09/10/2008

Volver arriba Ir abajo

[PC] Juego del snake, hecho por mi :P Empty Re: [PC] Juego del snake, hecho por mi :P

Mensaje por Kronos Lun Ene 26, 2009 3:35 pm

El juego me va demasiado rapido (es mas, no puedo jugar asi xD), lo de las colisiones esta bastante bien hecho, por eso podrias poner la web de donde te lo has pillado, para ver si hay mas info Wink.
Otra cosa las teclas del juego son W,S,D, para el jugador 1 y las flechas para el 2, es que yo me tire un rato para ver si lo hacia funcionar jejeje.
Saludos
Kronos
Kronos
Erudito

Masculino
Cantidad de envíos : 483
Edad : 34
Localización : Aulario B3
Fecha de inscripción : 09/10/2008

Volver arriba Ir abajo

[PC] Juego del snake, hecho por mi :P Empty Re: [PC] Juego del snake, hecho por mi :P

Mensaje por Amonshy Lun Ene 26, 2009 6:00 pm

Os dejo el código fuente:

Código:
#include <windows.h>
#include <dsound.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include <math.h>
#include <string.h>

void setupGraphics(int, char**);         // init GLUT and OpenGL
void animateCallback();               // main game loop
void displayCallback();               // redraw screen
void reshapeCallback(int, int);            // resize screen
void keyboardCallback(unsigned char, int, int);      // key pressed
void keyboardUpCallback(unsigned char, int, int);   // key released   
void specialCallback(int, int, int);         // non-ascii key press
void specialUpCallback(int, int, int);         // non-ascii key release
void visibilityCallback(int);            // if window visible
void refreshScore();               // refresh scoreboard
void setupSound();               // init DirectSound
LPDIRECTSOUNDBUFFER createSound(double, double);   // generate sound clip
void playSound(LPDIRECTSOUNDBUFFER);         // play sound clip

// sound variables

LPDIRECTSOUNDBUFFER lpDSB1, lpDSB2, lpDSB3;
LPDIRECTSOUND lpDS;
PCMWAVEFORMAT pcmwf;
int soundEnabled = FALSE;

// graphics variables

HWND hWnd;               // window handle
int windowId = -1;            // GLUT window ID
int viewportWidth = -1;            // screen width
int viewportHeight = -1;         // screen height
int visibilityState = GLUT_NOT_VISIBLE;      // if window visible

// player 1 & 2

#define PLAYER_ONE 0
#define PLAYER_TWO 1

// game states

#define GAME_STOPPED 0
#define GAME_ACTIVE 1
#define BALL_MISSED 2

// player 1 & 2 variables

float p1 = 0.0f, p2 = 0.0f;      // player 1 & 2 y positions
float p1v = 0.0f, p2v = 0.0f;      // player 1 & 2 y velocities

// ball variables

float bx = 0.0f, by = 0.0f;      // ball x, y position
float vx = 0.0f, vy = 0.0f;      // ball velocity

// initial game state

int gameState = GAME_STOPPED;
int nextPlayer = PLAYER_ONE;
int playerOnePoints = 0;
int playerTwoPoints = 0;
int lastTickCount = 0;

// dimensions and constants

#define BALL_SPEED 2.663f
#define PADDLE_SPEED 1.856f
#define PADDLE_OFFSET 0.923f
#define PADDLE_WIDTH 0.021f
#define PADDLE_HEIGHT 0.128f
#define WALL_OFFSET 0.735f
#define WALL_THICKNESS 0.037f
#define BALL_SIZE 0.025f
#define DEFLECT 0.081f
#define WALL (WALL_OFFSET - WALL_THICKNESS - BALL_SIZE)
#define PLANE (PADDLE_OFFSET - PADDLE_WIDTH - BALL_SIZE)

// text font

void *font = GLUT_BITMAP_TIMES_ROMAN_24;
char scoreString[16];
int scoreLength;
double scoreWidth;

// main loop

void animateCallback() {
   float elapsedTime;
   int currentTickCount;
   float displacement, distance;
   float py, dx, dy;
   // get elapsed time
   currentTickCount = GetTickCount();
   elapsedTime = (float) (currentTickCount - lastTickCount) * 0.001f;   // in seconds
   lastTickCount = currentTickCount;
   // make sure elapsed time is in range
   if (elapsedTime < 0.001f)
      elapsedTime = 0.001f;
   if (elapsedTime > 0.1f)
      elapsedTime = 0.1f;
   // multiply ball velocity by elapsed time
   dx = vx * elapsedTime;
   dy = vy * elapsedTime;
   // move ball
   bx += dx;
   by += dy;
   // check if ball is colliding with wall
   if ((vy > 0.0f) && (by > WALL)) {
      playSound(lpDSB2);
      // correct ball position
      distance = by - WALL;      // y overshot
      by -= distance;         // subtract from y
      // calculate x displacement of same magnitude
      displacement = distance * dx / dy;
      bx -= displacement;      // subtract from x
      // negate y velocity (bounce)
      vy = -vy;
   }
   if ((vy < 0.0f) && (by < -WALL)) {
      playSound(lpDSB2);
      // correct ball position
      distance = -by - WALL;      // y overshot
      by += distance;         // add to y
      // calculate x displacement of same magnitude
      displacement = distance * dx / dy;
      bx -= displacement;      // subtract from x
      // negate y velocity (bounce)
      vy = -vy;
   }
   // move player two
   if (p2v != 0.0f) {
      if (p2v > 0.0f) {
         if (p2 < (WALL_OFFSET - WALL_THICKNESS - PADDLE_HEIGHT))
            p2 += p2v * elapsedTime;
      }
      else {
         if (p2 > (-WALL_OFFSET + WALL_THICKNESS + PADDLE_HEIGHT))
            p2 += p2v * elapsedTime;
      }
   }
   // move player one
   if (p1v != 0.0f) {
      if (p1v > 0.0f) {
         if (p1 < (WALL_OFFSET - WALL_THICKNESS - PADDLE_HEIGHT))
            p1 += p1v * elapsedTime;
      }
      else {
         if (p1 > (-WALL_OFFSET + WALL_THICKNESS + PADDLE_HEIGHT))
            p1 += p1v * elapsedTime;
      }
   }
   // check for collision with paddles
   if (gameState == GAME_ACTIVE) {
      // player two
      if ((vx > 0.0f) && (bx > PLANE)) {
         // figure out where ball crossed paddle plane
         distance = bx - PLANE;         // x overshot
         displacement = distance * dy / dx;   // y displacement of the same magnitude
         py = by - displacement;         // y position where ball crossed plane
         // calculate distance from where ball crossed plane to where paddle is.
         displacement = p2 - py;
         distance = (float) fabs((double) displacement);
         if (distance > (PADDLE_HEIGHT + BALL_SIZE)) {
            // player two missed ball
            gameState = BALL_MISSED;
            nextPlayer = PLAYER_TWO;
         }
         else {
            // player two returned ball, calculate new velocity
            playSound(lpDSB1);
            vy = BALL_SPEED * distance / (PADDLE_HEIGHT + BALL_SIZE + DEFLECT);
            vx = vy - BALL_SPEED;
            // get correct direction
            if (displacement > 0.0f)
               vy = -vy;
         }
      }   
      // player one
      if ((vx < 0.0f) && (bx < -PLANE)) {
         // figure out where ball crossed paddle plane
         distance = -bx - PLANE;         // x overshot
         displacement = distance * dy / dx;   // y displacement of the same magnitude
         py = by - displacement;         // y position where ball crossed plane
         // calculate distance from where ball crossed plane to where paddle is.
         displacement = p1 - py;
         distance = (float) fabs((double) displacement);
         if (distance > (PADDLE_HEIGHT + BALL_SIZE)) {
            // player one missed ball
            gameState = BALL_MISSED;
            nextPlayer = PLAYER_ONE;
         }
         else {
            // player one returned ball, calculate new velocity
            playSound(lpDSB1);
            vy = BALL_SPEED * distance / (PADDLE_HEIGHT + BALL_SIZE + DEFLECT);
            vx = BALL_SPEED - vy;
            if (displacement  > 0.0f)
               vy = -vy;
         }
      }
   }
   if (gameState == BALL_MISSED) {
      // reset ball once it moves out of view
      if ((vx > 0.0f) && (bx > (1.0f + BALL_SIZE))) {
         playSound(lpDSB3);
         gameState = GAME_STOPPED;
         bx = by = vx = vy = 0.0f;      // zero ball position/velocity
         playerOnePoints++;
         refreshScore();
      }
      if ((vx < 0.0f) && (bx < -(1.0f + BALL_SIZE))) {
         playSound(lpDSB3);
         gameState = GAME_STOPPED;
         bx = by = vx = vy = 0.0f;      // zero ball position/velocity
         playerTwoPoints++;
         refreshScore();
      }
   }   
   // only update the screen if window is visible
   if (visibilityState == GLUT_VISIBLE)
      glutPostRedisplay();
}

// draw screen

void displayCallback() {
   int i;
   double w, h;
   // clear screen
   glClear(GL_COLOR_BUFFER_BIT);
   // draw score
        glMatrixMode(GL_PROJECTION);
   glPushMatrix();
   glLoadIdentity();
   w = (double) viewportWidth;
   h = (double) viewportHeight;
        gluOrtho2D(0.0, w, 0.0, h);
   glMatrixMode(GL_MODELVIEW);
   glPushMatrix();
        glLoadIdentity();
   glRasterPos2d((w / 2.0) - (scoreWidth / 2.0), h * 0.9);
   for (i = 0; i < scoreLength; i++)
           glutBitmapCharacter(font, scoreString[i]);
        glMatrixMode(GL_PROJECTION);
   glPopMatrix();
   glMatrixMode(GL_MODELVIEW);
   glPopMatrix();
   // draw polygons
   glBegin(GL_QUADS);
   // draw top wall
   glVertex2f(1.0f, WALL_OFFSET + WALL_THICKNESS);
   glVertex2f(-1.0f, WALL_OFFSET + WALL_THICKNESS);
   glVertex2f(-1.0f, WALL_OFFSET - WALL_THICKNESS);
   glVertex2f(1.0f, WALL_OFFSET - WALL_THICKNESS);
   // draw bottom wall
   glVertex2f(1.0f, -WALL_OFFSET + WALL_THICKNESS);
   glVertex2f(-1.0f, -WALL_OFFSET + WALL_THICKNESS);
   glVertex2f(-1.0f, -WALL_OFFSET - WALL_THICKNESS);
   glVertex2f(1.0f, -WALL_OFFSET - WALL_THICKNESS);   
   // draw ball
   glVertex2f(bx + BALL_SIZE, by + BALL_SIZE);
   glVertex2f(bx - BALL_SIZE, by + BALL_SIZE);
   glVertex2f(bx - BALL_SIZE, by - BALL_SIZE);
   glVertex2f(bx + BALL_SIZE, by - BALL_SIZE);
   // draw player 2
   glVertex2f(PADDLE_OFFSET + PADDLE_WIDTH, p2 + PADDLE_HEIGHT);
   glVertex2f(PADDLE_OFFSET - PADDLE_WIDTH, p2 + PADDLE_HEIGHT);
   glVertex2f(PADDLE_OFFSET - PADDLE_WIDTH, p2 - PADDLE_HEIGHT);
   glVertex2f(PADDLE_OFFSET + PADDLE_WIDTH, p2 - PADDLE_HEIGHT);
   // draw player 1
   glVertex2f(-PADDLE_OFFSET + PADDLE_WIDTH, p1 + PADDLE_HEIGHT);
   glVertex2f(-PADDLE_OFFSET - PADDLE_WIDTH, p1 + PADDLE_HEIGHT);
   glVertex2f(-PADDLE_OFFSET - PADDLE_WIDTH, p1 - PADDLE_HEIGHT);
   glVertex2f(-PADDLE_OFFSET + PADDLE_WIDTH, p1 - PADDLE_HEIGHT);
   glEnd();
   glFlush();
   glutSwapBuffers();
}

// keyboard input

void keyboardCallback(unsigned char key, int x, int y) {
   // player 1 key press
   switch (key) {
      // player one
      case 'W':
      case 'w':
         p1v = PADDLE_SPEED;
         break;
      case 'S':
      case 's':
         p1v = -PADDLE_SPEED;
         break;
      case 'D':
      case 'd':
         if ((gameState == GAME_STOPPED) && (nextPlayer == PLAYER_ONE)) {
            if (playerTwoPoints == 10) {
               playerOnePoints = 0;
               playerTwoPoints = 0;
               refreshScore();
            }
            vx = -BALL_SPEED;
            gameState = GAME_ACTIVE;
         }
         break;
      case 27:   // ESCAPE
         exit(0);
   }
}

void specialCallback(int key, int x, int y) {
   // player 2 key press
   switch (key) {
      // player two
      case GLUT_KEY_UP:
         p2v = PADDLE_SPEED;
         break;
      case GLUT_KEY_DOWN:
         p2v = -PADDLE_SPEED;
         break;
      case GLUT_KEY_LEFT:
         if ((gameState == GAME_STOPPED) && (nextPlayer == PLAYER_TWO)) {
            if (playerOnePoints == 10) {
               playerOnePoints = 0;
               playerTwoPoints = 0;
               refreshScore();
            }
            vx = BALL_SPEED;
            gameState = GAME_ACTIVE;
         }
         break;
   }
}

void keyboardUpCallback(unsigned char key, int x, int y) {
   // player 1 key release
   switch (key) {
      case 'W':
      case 'w' :
         if (p1v > 0.0f)
            p1v = 0.0f;
         break;
      case 'S' :
      case 's' :
         if (p1v < 0.0f)
            p1v = 0.0f;
         break;
   }
}

void specialUpCallback(int key, int x, int y){
   // player 2 key release
   switch (key) {
      case GLUT_KEY_UP:
         if (p2v > 0.0f)
            p2v = 0.0f;
         break;
      case GLUT_KEY_DOWN:
         if (p2v < 0.0f)
            p2v = 0.0f;
         break;
   }
}

void refreshScore() {
   int i;
   sprintf(scoreString, "%d/%d", playerOnePoints, playerTwoPoints);
   scoreLength = strlen(scoreString);
   scoreWidth = 0.0;
   for (i = 0; i < scoreLength; i++)
      scoreWidth += (double) glutBitmapWidth(font, scoreString[i]);
}

void reshapeCallback(int width, int height) {
   viewportWidth = width;
   viewportHeight = height;
   glViewport(0, 0, viewportWidth, viewportHeight);
   glutPostRedisplay();
}

void setupGraphics(int argc, char **argv) {   
   GLfloat ambientLight[] = { 1.0f, 1.0f, 1.0f, 1.0f };
   GLfloat emissiveLight[] = { 0.0f, 0.0f, 0.0f, 1.0f };
   GLfloat diffuseLight[] = { 1.0f, 1.0f, 1.0f, 1.0f };
   GLfloat specularLight[] = { 1.0f, 1.0f, 1.0f, 1.0f };

   GLfloat materialAmbient[] = { 0.1f, 0.1f, 0.1f, 1.0f };
   GLfloat materialDiffuse[] = { 0.1f, 0.1f, 0.1f, 1.0f };
   GLfloat materialEmission[] = { 0.0f, 0.0f, 0.0f, 1.0f };
   GLfloat materialSpecular[] = { 1.0f, 1.0f, 1.0f, 1.0f };

   GLfloat lightPosition[] = { 0.0f, 0.0f, 1.0f, 1.0f };
   
   // setup GLUT

   viewportWidth = 374; viewportHeight = 200;
   glutInitWindowSize(viewportWidth, viewportHeight);
   glutInitWindowPosition(70, 70);
   glutInit(&argc, argv);
   glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
   windowId = glutCreateWindow("Pong");
   glutSetWindow(windowId);
   glutDisplayFunc(displayCallback);
   glutReshapeFunc(reshapeCallback);
   glutVisibilityFunc(visibilityCallback);
   glutKeyboardFunc(keyboardCallback);
   glutKeyboardUpFunc(keyboardUpCallback);
   glutSpecialFunc(specialCallback);
   glutSpecialUpFunc(specialUpCallback);
   glutIdleFunc(animateCallback);
   glutMouseFunc(NULL);
   glutMotionFunc(NULL);
   glutPassiveMotionFunc(NULL);
   glutShowWindow();

   // get window handle

   hWnd = FindWindow(NULL, "Pong");

   // setup OpenGL

   glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
   glEnable(GL_LIGHTING);
   glLightfv(GL_LIGHT0, GL_AMBIENT, ambientLight);
   glLightfv(GL_LIGHT0, GL_EMISSION, emissiveLight);
   glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseLight);
   glLightfv(GL_LIGHT0, GL_SPECULAR, specularLight);
   glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);
   glEnable(GL_LIGHT0);
   glEnable(GL_BLEND);
   glEnable(GL_COLOR_MATERIAL);
   glShadeModel(GL_SMOOTH);
   glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
   glMaterialfv(GL_FRONT, GL_AMBIENT, materialAmbient);
   glMaterialfv(GL_FRONT, GL_DIFFUSE, materialDiffuse);
   glMaterialfv(GL_FRONT, GL_EMISSION, materialEmission);
   glMaterialfv(GL_FRONT, GL_SPECULAR, materialSpecular);
   glMateriali(GL_FRONT, GL_SHININESS, 128);
   glDisable(GL_DEPTH_TEST);
   glDisable(GL_NORMALIZE);
   glMatrixMode(GL_MODELVIEW);
   glLoadIdentity();
   glColor4f(1.0f, 0.0f, 0.0f, 1.0f);
}

void visibilityCallback(int state) {
   visibilityState = state;
   if (state == GLUT_VISIBLE)
      glutPostRedisplay();      
}

void setupSound() {
   if (DirectSoundCreate(NULL, &lpDS, NULL) == DS_OK) {
      if (IDirectSound_SetCooperativeLevel(lpDS, hWnd, DSSCL_NORMAL) == DS_OK) {
         // set up wave format structure
         memset(&pcmwf, 0, sizeof(PCMWAVEFORMAT));
         pcmwf.wf.wFormatTag = WAVE_FORMAT_PCM;
         pcmwf.wf.nChannels = 1;
         pcmwf.wf.nSamplesPerSec = 44100;
         pcmwf.wBitsPerSample = 16;
         pcmwf.wf.nBlockAlign = pcmwf.wf.nChannels * pcmwf.wBitsPerSample / 8;
         pcmwf.wf.nAvgBytesPerSec = pcmwf.wf.nSamplesPerSec * pcmwf.wf.nBlockAlign;
         soundEnabled = TRUE;
      }
   }      
}

LPDIRECTSOUNDBUFFER createSound(double frequency, double seconds) {
   LPDIRECTSOUNDBUFFER lpDSB;
   DSBUFFERDESC dsbdesc;
   HRESULT hr;
   DWORD samples, bytes;
   unsigned short *buffer;
   double angle, value, increment;
   int i;
   // locked area of direct sound buffer
   LPVOID lpvPtr1, lpvPtr2;
   DWORD dwBytes1, dwBytes2;
   // make sure direct sound was initialized
   if (!soundEnabled)
      return;
   // set up direct sound buffer descriptor
   memset(&dsbdesc, 0, sizeof(DSBUFFERDESC));
   dsbdesc.dwSize = sizeof(DSBUFFERDESC);
   dsbdesc.dwFlags = DSBCAPS_CTRLDEFAULT;
   samples = (int) (44100.0 * seconds);
   bytes = pcmwf.wf.nBlockAlign * samples;
   dsbdesc.dwBufferBytes = bytes;
   dsbdesc.lpwfxFormat = (LPWAVEFORMATEX) &pcmwf;
   // create direct sound buffer
   hr = IDirectSound_CreateSoundBuffer(lpDS, &dsbdesc, &lpDSB, NULL);
   if (!SUCCEEDED(hr)) {
      soundEnabled = FALSE;
      return;
   }
   // lock buffer
   hr = IDirectSoundBuffer_Lock(lpDSB, 0, bytes, &lpvPtr1, &dwBytes1, &lpvPtr2, &dwBytes2, 0);
   if (hr == DSERR_BUFFERLOST) {
      IDirectSoundBuffer_Restore(lpDSB);
      hr = IDirectSoundBuffer_Lock(lpDSB, 0, bytes, &lpvPtr1,
         &dwBytes1, &lpvPtr2, &dwBytes2, 0);
   }
   // write to buffer
   if (SUCCEEDED(hr)) {
      buffer = (unsigned short *) lpvPtr1;
      angle = 0.0;
      increment = frequency * seconds / (2.0 * 3.14159);
      for (i = 0; i < samples; i++) {
         value = sin(angle);
         buffer[i] = (unsigned short) ((value + 1.0) * 32768.0);
         angle += increment;
      }
      IDirectSoundBuffer_Unlock(lpDSB, lpvPtr1, dwBytes1, lpvPtr2, dwBytes2);
   }
   else {
      soundEnabled = FALSE;
   }
   return lpDSB;
}

void playSound(LPDIRECTSOUNDBUFFER lpDSB) {
   if (!soundEnabled)
      return;
   IDirectSoundBuffer_SetCurrentPosition(lpDSB, 0);
   if (!SUCCEEDED(IDirectSoundBuffer_Play(lpDSB, 0, 0, 0)))
      soundEnabled = FALSE;
}

int main(int argc, char **argv) {
   setupGraphics(argc, argv);
   setupSound();
   lpDSB1 = createSound(3000.0, 0.12);
   lpDSB2 = createSound(1200.0, 0.04);
   lpDSB3 = createSound(750.0, 0.23);
   refreshScore();
   lastTickCount = GetTickCount();
   glutMainLoop();
   return 0;
}

Un saludo.

PD: La extensión del archivo es .c
Amonshy
Amonshy
Maestro

Masculino
Cantidad de envíos : 260
Edad : 34
Localización : Córdoba
Empleo /Ocio : Estudiante
Fecha de inscripción : 09/10/2008

Volver arriba Ir abajo

[PC] Juego del snake, hecho por mi :P Empty Re: [PC] Juego del snake, hecho por mi :P

Mensaje por Kronos Lun Ene 26, 2009 7:42 pm

Thanks Wink
Kronos
Kronos
Erudito

Masculino
Cantidad de envíos : 483
Edad : 34
Localización : Aulario B3
Fecha de inscripción : 09/10/2008

Volver arriba Ir abajo

[PC] Juego del snake, hecho por mi :P Empty Re: [PC] Juego del snake, hecho por mi :P

Mensaje por ReyLith Lun Ene 26, 2009 11:53 pm

Coño tio... crei que lo habias hecho tú lol!
ReyLith
ReyLith
Erudito

Masculino
Cantidad de envíos : 382
Edad : 34
Localización : La concha de la Lora
Fecha de inscripción : 09/10/2008

Volver arriba Ir abajo

[PC] Juego del snake, hecho por mi :P Empty Re: [PC] Juego del snake, hecho por mi :P

Mensaje por Kronos Mar Ene 27, 2009 12:19 am

Jjajajaj, en verano ya nos picaremos ha hacer juegos (yo por lo menos xD)
Kronos
Kronos
Erudito

Masculino
Cantidad de envíos : 483
Edad : 34
Localización : Aulario B3
Fecha de inscripción : 09/10/2008

Volver arriba Ir abajo

[PC] Juego del snake, hecho por mi :P Empty Re: [PC] Juego del snake, hecho por mi :P

Mensaje por Amonshy Mar Ene 27, 2009 1:42 am

ReyLith escribió:Coño tio... crei que lo habias hecho tú lol!

No hay tiempo para eso ahora mismo...

Un saludo.
Amonshy
Amonshy
Maestro

Masculino
Cantidad de envíos : 260
Edad : 34
Localización : Córdoba
Empleo /Ocio : Estudiante
Fecha de inscripción : 09/10/2008

Volver arriba Ir abajo

[PC] Juego del snake, hecho por mi :P Empty Re: [PC] Juego del snake, hecho por mi :P

Mensaje por Admin Mar Ene 27, 2009 11:25 am

Gracias postear el codigo, hay vienen funciones de C muy interesantes. Wink

Admin
Admin

Masculino
Cantidad de envíos : 568
Edad : 35
Fecha de inscripción : 08/10/2008

https://sistematicos.forosactivos.net

Volver arriba Ir abajo

[PC] Juego del snake, hecho por mi :P Empty Re: [PC] Juego del snake, hecho por mi :P

Mensaje por Kronos Mar Ene 27, 2009 2:29 pm

Por cierto alguien puede compilarlo con el dev c++, a mi me sale un error.
Suerte con el estudio Wink
Kronos
Kronos
Erudito

Masculino
Cantidad de envíos : 483
Edad : 34
Localización : Aulario B3
Fecha de inscripción : 09/10/2008

Volver arriba Ir abajo

[PC] Juego del snake, hecho por mi :P Empty Re: [PC] Juego del snake, hecho por mi :P

Mensaje por Contenido patrocinado


Contenido patrocinado


Volver arriba Ir abajo

Volver arriba

- Temas similares

 :: Ocio :: Videojuegos

 
Permisos de este foro:
No puedes responder a temas en este foro.