|
Mostrar Temas
|
Páginas: [1]
|
1
|
Media / Juegos y Consolas / Juego SDL
|
en: 21 Enero 2017, 13:52 pm
|
Hola gente, Estamos haciendo con un grupo de alumnos de clase un juego con SDL 2.0 y ahora tengo un problema a la hora de implementar el movimiento de el jugador en un método propio de su clase. La estructura de clases es la siguiente: Entity(Clase padre) es donde contiene el método move(); Player(Clase hija) Hereda la clase move() de Entity i el resto de sus mètodos y atributos. Ahora me viene el problema (Que no se si es posible realizar lo que quiero hacer), la manera en la cual he pensado hacer el mètodo és la siguiente: void CPlayer::movee(SDL_Event evento) { switch (evento.key.keysym.sym) { //Eventos de teclado depende del que se clique un movimiento o otro case SDLK_UP: if (y > 0) //Se resta la posicion y y = y - 10; break; case SDLK_DOWN: if (y < 340) //Se suma la posicion y y = y + 10; break; case SDLK_LEFT: //Se resta la posicion x if (x > 0) x = x - 10; break; case SDLK_RIGHT: //Se resta la posicion y if (x < 540) x = x + 10; break; } }
Como veis se tiene que pasar como paràmetros un dato del tipo SDL_Event, pero como en la clase padre no esta definido me da error, mi pregunta es si hay alguna manera de hacer override o otra cosa o de lo contrario alguna idea de como implementar el movimiento en la clase Player. Aquí les dejare todo el còdigo de todo lo que està implicado. Entity.cpp#include "Entity.h" #include "Sprite.h" CEntity::CEntity() { } CEntity::CEntity(char * file, int x, int y, int hight, int width, SDL_Renderer * window) { this->file = file; this->x = x; this->y = y; this->hight = hight; this->width = width; this->window = window; } CEntity::~CEntity() { } int CEntity::get_x() { return x; } int CEntity::get_y() { return y; } int CEntity::get_hight() { return hight; } int CEntity::get_width() { return width; } char CEntity::get_file() { return *file; } //Dona erroer es te que mirar, tot i que per el moment no es necessari mes endevant pot ser que ho necessitem /*SDL_Renderer CEntity::get_window() { return window; }*/ void CEntity::set_x(int x) { this->x = x; } void CEntity::set_y(int y) { this->y = y; } void CEntity::set_hight(int hight) { this->hight = hight; } void CEntity::set_width(int width) { this->width = width; } void CEntity::set_file(char* file) { this->file = file; } void CEntity::set_window(SDL_Renderer* window) { this->window = window; } void CEntity::load() { //Carga la imagen del pj image = Sprite::Load(file, window); } void CEntity::draw() { //Dibuja el pj Sprite::Draw(window, image, x, y, width, hight); }
Entity.h#pragma once #include <SDL.h> class CEntity { public: CEntity(); CEntity(char * file, int x, int y, int hight, int width, SDL_Renderer* window); ~CEntity(); int get_x(); int get_y(); int get_hight(); int get_width(); SDL_Renderer get_window(); char get_file(); void set_file(char* file); void set_window(SDL_Renderer* Window); void set_x(int x); void set_y(int y); void set_hight(int hight); void set_width(int width); virtual void move() = 0; void load(); void draw(); private: SDL_Renderer* window; SDL_Texture* image; char* file; protected: int hight; int width; int x; int y; };
Player.cpp#include "Player.h" #include "Entity.h" CPlayer::CPlayer(char * file, int x, int y, int hight, int width, SDL_Renderer * window) : CEntity(file, x, y, hight, width, window) { } CPlayer::CPlayer() { } void CPlayer::movee(SDL_Event evento) { switch (evento.key.keysym.sym) { //Eventos de teclado depende del que se clique un movimiento o otro case SDLK_UP: if (y > 0) //Se resta la posicion y y = y - 10; break; case SDLK_DOWN: if (y < 340) //Se suma la posicion y y = y + 10; break; case SDLK_LEFT: //Se resta la posicion x if (x > 0) x = x - 10; break; case SDLK_RIGHT: //Se resta la posicion y if (x < 540) x = x + 10; break; } } void CPlayer::move() { }
Player.h#pragma once #include<SDL.h> #include"Sprite.h" #include "Entity.h" class CPlayer : public CEntity { public: CPlayer(char * file, int x, int y, int hight, int width, SDL_Renderer* window); CPlayer(); void movee(SDL_Event evento); void move(); private: };
PlayState.cpp#include <stdio.h> #include "SDL.h" #include "Game.h" #include "PlayState.h" #include "PauseState.h" #include "Player.h" PlayState PlayState::m_PlayState; void PlayState::Init(Game* game) { playSprite = NULL; playSprite = Sprite::Load("sprites/playstate.bmp", game->GetRenderer()); //Constructor del jugador, se passa la ubicacion de la imagen i sus datos igual que //el renderer donde se carga player = CPlayer("sprites/macaco.bmp", 200, 200, 64, 64, game->GetRenderer()); //Defino la posicion inicial del enemigo enemy_x = posicions_x[0]; enemy_y = posicions_y[0]; //Cargo la imagen del enemigo enemy = Sprite::Load("sprites/crab.bmp", game->GetRenderer()); //Cargo la imagen del jugador player.load(); printf("PlayState Init Successful\n"); } void PlayState::Clean() { printf("PlayState Clean Successful\n"); } void PlayState::Pause() { printf("PlayState Paused\n"); } void PlayState::Resume() { printf("PlayState Resumed\n"); } void PlayState::HandleEvents(Game* game) { SDL_Event event; if (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: game->Quit(); break; case SDL_KEYDOWN: switch (event.key.keysym.sym) { //Eventos de teclado depende del que se clique un movimiento o otro case SDLK_SPACE: game->PushState(PauseState::Instance()); break; } player.movee(event); //Comproba el contador per el seguiment del enemic if (cont < 8) { //Guarda les posicions anterior del pj a les cordenades del enemic enemy_x = posicions_x[cont]; enemy_y = posicions_y[cont]; //Esborra les cordenades utilitzades ara i les actualitza amb les actuals posicions_x[cont] = player.get_x(); posicions_y[cont] = player.get_y(); //Suma el contador cont++; } else { //El contador arriba al maxim i es torna a possar a 0 cont = 0; } } } } void PlayState::Update(Game* game) { } void PlayState::Draw(Game* game) { Sprite::DrawFullScreen(game->GetRenderer(), playSprite); //Dibuja el enemigo Sprite::Draw(game->GetRenderer(), enemy, enemy_x, enemy_y, 64, 64); //Dibuja el personaje player.draw(); SDL_RenderPresent(game->GetRenderer()); }
En este ejemplo que he puesto hay un método propio de la clase Player llamado movee que es funcional y actualmente funciona perfectamente, pero claro yo lo que quiero es que lo pueda heredar de la clase entity y en la propia clase Player poder modificarlo como esta aquí, ya que el método move() de la clase Entity también serà utilizado por los enemigos clase Enemy. Gracias por vuestra ayuda, Si teneis alguna otra solución o alguna idea de como realizar el movimiento se lo agradezco. Saludos!
|
|
|
2
|
Programación / Java / Ejercicio Java
|
en: 13 Octubre 2016, 12:18 pm
|
Buenas, tengo que realizar un ejercicio en java. El ejercicio consiste en cifrar un documento binario con el mètodo XOR. Yo tengo echo el codigo pero solo me funciona en extensión .txt aquí lo adjunto. package xor; import java.io.FileReader; import java.io.FileWriter; import java.util.Scanner; public class XOR { public static void main (String[] args ) { try { System. out. println("Introdueix el nom de l'arxiu: "); System. out. println("Introdueix el nom de l'arxiu encriptat: "); System. out. println("Introdueix la contrasenya de encriptació: "); int tamaño = password.length(); int cont = 0; if (!nomArxiu.equals(nomArxiu2)) { int caracter = fr.read(); while(caracter != -1) { int encrip = caracter ^ password.charAt(cont); //cifra la letra fw.write(encrip); //escribe la letra en el fichero caracter = fr.read(); //lee el siguiente caracter if (cont < tamaño - 1) { cont++; } else { cont = 0; } } fr.close(); fw.close(); } } { System. out. println("e.toString"); } } }
Gracias. Un saludo.
|
|
|
3
|
Programación / Programación C/C++ / Programación videojuegos C++
|
en: 19 Septiembre 2016, 22:30 pm
|
Buenas, quería pedir ayuda, en como empezar a programar un vídeojuego en C++. Me interesa lo que es la interficie gráfica. Si me pudieran recomendar algún libro me ayudarían mucho. Gracias y Saludos
|
|
|
4
|
Programación / Programación C/C++ / Juego naves error código
|
en: 14 Marzo 2016, 09:56 am
|
Hola, tengo un problema el otro día estaba realizando un tutorial de como crear un juego en c++ y una vez terminado me funcionaba perfectamente (visual studio 2015), pero en ejecutarlo en dev c++ me daba otros errores... si me pudieran echar un vistazo en el código y ayudarme se lo agradecería. Erro linea 256 y línea 270. Aquí adjunto el código: #include <stdio.h> #include <windows.h> #include <conio.h> #include <stdlib.h> #include <list> using namespace std; #define ARRIBA 72 #define IZQUIERDA 75 #define DERECHA 77 #define ABAJO 80 void fflush_in() { int ch; while ((ch = fgetc(stdin)) != EOF && ch != '\n') {} } void gotoxy(int x, int y) { //HANDLE es el nombre que recibe la consola, i l'he ponemos el nombre de que queramos //en este caso hCon que es el que se pone por defecto. HANDLE hCon; //Coje el identificador de la ventana (GetStdHandle) hCon = GetStdHandle(STD_OUTPUT_HANDLE); //Creamos las cordenadas. COORD dwPos; dwPos.X = x; dwPos.Y = y; SetConsoleCursorPosition(hCon, dwPos); } void ocultarCursor() { HANDLE hCon; hCon = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_CURSOR_INFO cci; cci.dwSize = 2; cci.bVisible = FALSE; SetConsoleCursorInfo(hCon, &cci); } void pintarLimites() { for (int i = 2; i < 78; i++) { gotoxy(i, 3); printf("%c", 205); gotoxy(i, 33); printf("%c", 205); } for (int i = 4; i < 33; i++) { gotoxy(2, i); printf("%c", 186); gotoxy(77, i); printf("%c", 186); } gotoxy(2, 3); printf("%c", 201); gotoxy(2, 33); printf("%c", 200); gotoxy(77, 3); printf("%c", 187); gotoxy(77, 33); printf("%c", 188); } class NAVE { int x, y; int corazones; int vidas; public: NAVE(int _x, int _y, int _corazones, int _vidas) : x(_x), y(_y), corazones(_corazones), vidas(_vidas) {} int X() { return x; } int Y() { return y; } int VID() { return vidas; } void pCorazon() { corazones--; } void gCorazon() { if (corazones < 3)corazones++; } void pintar(); void borrar(); void mover(); void pintarCorazones(); void morir(); }; class AST { int x, y; public: AST(int _x, int _y) : x(_x), y(_y) {} void pintar(); void mover(); void choque(class NAVE &N); void borrar(); int X() { return x; } int Y() { return y; } }; class VIDA { int x, y; public: VIDA(int _x, int _y) : x(_x), y(_y) {} void pintar(); void mover(); void choque(class NAVE &N); void borrar(); }; class BALA { int x, y; public: BALA(int _x, int _y) : x(_x), y(_y) {}; int X() { return x; } int Y() { return y; } void mover(); bool fuera(); }; /* ALTERNATIVA a : x(_x), y(_y) {} NAVE::NAVE(int _x, int _y) { x = _x; y = _y; }*/ void NAVE::pintar() { gotoxy(x, y); printf(" %c", 30); gotoxy(x, y + 1); printf(" %c%c%c", 40, 207, 41); gotoxy(x, y + 2); printf("%c%c %c%c", 30, 190, 190, 30); system("color 7"); } void NAVE::borrar() { gotoxy(x, y); printf(" "); gotoxy(x, y + 1); printf(" "); gotoxy(x, y + 2); printf(" "); } void NAVE::mover() { if (kbhit()) { char tecla = getch(); borrar(); if (tecla == IZQUIERDA && x > 3) x--; if (tecla == DERECHA && x + 6 < 77) x++; if (tecla == ARRIBA && y > 4) y--; if (tecla == ABAJO && y + 3 < 33) y++; pintar(); pintarCorazones(); } } void NAVE::pintarCorazones() { gotoxy(50, 2); printf("VIDAS %d", vidas); gotoxy(64, 2); printf("Salud"); gotoxy(70, 2); printf(" "); for (int i = 0; i < corazones; i++) { gotoxy(70 + i, 2); printf("%c\r", 03); } } void NAVE::morir() { if (corazones == 0) { borrar(); gotoxy(x, y); printf(" * "); gotoxy(x, y + 1); printf("** **"); gotoxy(x, y + 2); printf(" * "); Sleep(200); borrar(); gotoxy(x, y); printf("* * *"); gotoxy(x, y + 1); printf(" * "); gotoxy(x, y + 2); printf("* * *"); Sleep(200); borrar(); vidas--; corazones = 3; pintarCorazones(); pintar(); } } void AST::pintar() { gotoxy(x, y); printf("%c", 'o'); } void AST::mover() { gotoxy(x, y); printf(" "); y++; if (y > 32) { x = rand() % 71 + 4; y = 4; } pintar(); } void AST::choque(class NAVE &N) { if (x >= N.X() && x < N.X() + 6 && y >= N.Y() && y <= N.Y() + 2) { N.pCorazon(); borrar(); N.pintar(); N.pintarCorazones(); x = rand() % 71 + 4; y = 4; } } void AST::borrar() { gotoxy(x, y); printf(" "); } void VIDA::pintar() { gotoxy(x, y); printf("%c", 3); } void VIDA::mover() { gotoxy(x, y); printf(" "); y++; if (y > 32) { x = rand() % 71 + 4; y = 4; } pintar(); } void VIDA::choque(class NAVE &N) { if (x >= N.X() && x < N.X() + 6 && y >= N.Y() && y <= N.Y() + 2) { N.gCorazon(); N.pintarCorazones(); borrar(); N.pintar(); x = rand() % 71 + 4; y = 4; } } void VIDA::borrar() { gotoxy(x, y); printf(" "); } void BALA::mover() { gotoxy(x, y); printf(" "); y--; gotoxy(x, y); printf("*"); } bool BALA::fuera() { if (y == 4) { return true; } else { return false; } } int main() { char tecla; do { ocultarCursor(); pintarLimites(); list<AST*> A; list<AST*>::iterator itA; for (int i = 0; i < 5; i++) { A.push_back(new AST(rand() % 75 + 3, rand() % 5 + 4)); } NAVE N(15, 25, 3, 3); VIDA vit(15, 8); list<BALA*> B; list<BALA*>::iterator it; N.pintar(); int puntos = 0; bool game_over = false; while (!game_over) { gotoxy(4, 2); printf("PUNTOS %d", puntos); if (kbhit()) { char tecla = getch(); if (tecla == 'a') { B.push_back(new BALA(N.X() + 2, N.Y() - 1)); } } for (it = B.begin(); it != B.end();) { (*it)->mover(); if ((*it)->fuera()) { gotoxy((*it)>X(), (*it)>Y()); printf(" "); delete(*it); it = B.erase(it); } else { it++; } } N.mover(); vit.mover(); vit.choque(N); for (itA = A.begin(); itA != A.end(); itA++) { (*itA)->mover(); (*itA)->choque(N); } for (itA = A.begin(); itA != A.end(); itA++) { for (it = B.begin(); it != B.end();) { if ((*itA)>X() == (*it)>X() && ((*itA)>Y() + 1 == (*it)>Y() || (*itA)>Y() == (*it)>Y())) { gotoxy((*it)>X(), (*it)>Y()); printf(" "); delete (*it); it = B.erase(it); A.push_back(new AST(rand() % 74 + 3, 4)); gotoxy((*itA)>X(), (*itA)>Y()); printf(" "); delete (*itA); itA = A.erase(itA); puntos = puntos + 5; } else { it++; } } } if (N.VID() < 0) { game_over = true; } N.morir(); Sleep(60); } gotoxy(4, 35); printf("\nGAME OVER\n"); printf("JUGAR DE 9? [S/N]\n"); do { scanf("%c", &tecla); fflush_in(); tecla = towlower(tecla); if (tecla != 's' && tecla != 'n') { printf("Solo [S/N]"); } } while (tecla != 's' && tecla != 'n'); system("cls"); } while (tecla != 'n'); return 0; }
|
|
|
6
|
Programación / Programación C/C++ / Error al comparar datos
|
en: 3 Diciembre 2015, 10:09 am
|
Buenas a todos, el otro día hice un programa y tuve un problema... El programa trata de que pongas un numero aleatorio y que tu introduzcas un valor y te diga si lo has acertado o no. El problema viene en cuanto introduces el dato, Si pones numero superior a 10 o menor a 0 de error, si pones una letra también da error, pero si pones primero un numero seguido de una letra me lo acepta como numero. Y quiero solucionar esto de manera que si tu pones un numero que no sea valido tal sea seguido de letra o no te de error. No se si me he explicado bien... Aquí dejo el código: #include <stdio.h> #include <stdlib.h> #include <time.h> #include <ctype.h> void main() { srand(time(NULL)); int r, res, i; bool exit = false, ok; char retry; printf("JOC DE ENDEVINAR EL NUMERO\n\n"); do { r = (rand() % 10) + 1; i = 0; do{ printf("Introdueix un numero (1-10): "); /*-------------------------------------------*/ /*-------------------------------------------*/ /*-------------------------------------------*/ ok = scanf("%i", &res); /*-------------------------------------------*/ /*-------------------------------------------*/ /*-------------------------------------------*/ while (getchar() != '\n'); if (ok && res >= 1 && res <= 10 ) { if (res < r) { printf("Nº massa baix\n"); } else if (res > r) { printf("Nº massa alt\n"); } else if (res == r) { printf("Has encertat!\n"); exit = true; } i++; } else { printf("No has introduit un valor disponible\n"); } }while (i < 12 && exit == false ); printf("Intents realitzats: %d\n", i); exit = false; do{ printf("Vols tornar a jugar? (Y/N): "); scanf("%c", &retry); retry = towlower(retry); while (getchar() != '\n'); if (retry == 'n') { exit = true; } else if (retry == 'y') { } else { printf("Introdueix una opcioo vàlida\n"); } }while (retry != 'y' && retry != 'n'); } while (exit == false); system("pause"); }
Gracias por su ayuda. Un saludo.
|
|
|
7
|
Programación / Programación C/C++ / Problema con el código.
|
en: 4 Noviembre 2015, 09:21 am
|
Buenas, he echo este programa y el código me parece correcto però me da un error. El programa que e echo consiste en introducir la hora semanales, si son 40 el sueldo por hora es normal, si son 48 hora, 8 horas extra se pagan el doble (las extras) i a partir de más horas extras esas se pagan al triple. Aqui les adjunto el código que he realizado(Compliado en Visual Studio 2015). Un saludo. #include <stdio.h> #include <stdlib.h> void main() { int hores, preu, total; printf("Quantes hores has fet a la setmana? "); scanf("%d", &hores); printf("Quant cobres per hora"); scanf("%d", preu); if (hores <= 40) { total = hores*preu; printf("El sou teu és de %d euros a la setmana\n", total); } else if (hores <= 48) { total = (40 * preu) + ((hores - 40)*preu * 2); printf("El teu sou és de %d euros a la setmana\n", total); } else if (hores > 48) { (total = 40 * preu) + ((hores - 40)*preu * 2) + ((hores - 48)*preu * 2); printf("El teu sou és de %d euros a la setmana\n", total); } }
|
|
|
|
|
|
|