elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Curso de javascript por TickTack


  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:
Código
  1. void CPlayer::movee(SDL_Event evento) {
  2. switch (evento.key.keysym.sym) {
  3.  
  4. //Eventos de teclado depende del que se clique un movimiento o otro
  5. case SDLK_UP:
  6. if (y > 0)
  7. //Se resta la posicion y
  8. y = y - 10;
  9.  
  10. break;
  11. case SDLK_DOWN:
  12. if (y < 340)
  13. //Se suma la posicion y
  14. y = y + 10;
  15.  
  16. break;
  17. case SDLK_LEFT:
  18. //Se resta la posicion x
  19. if (x > 0)
  20. x = x - 10;
  21.  
  22. break;
  23. case SDLK_RIGHT:
  24. //Se resta la posicion y
  25. if (x < 540)
  26. x = x + 10;
  27. break;
  28. }
  29. }

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
Código
  1. #include "Entity.h"
  2. #include "Sprite.h"
  3.  
  4.  
  5. CEntity::CEntity()
  6. {
  7. }
  8.  
  9. CEntity::CEntity(char * file, int x, int y, int hight, int width, SDL_Renderer * window)
  10. {
  11. this->file = file;
  12. this->x = x;
  13. this->y = y;
  14. this->hight = hight;
  15. this->width = width;
  16. this->window = window;
  17. }
  18.  
  19.  
  20. CEntity::~CEntity()
  21. {
  22. }
  23.  
  24. int CEntity::get_x()
  25. {
  26. return x;
  27. }
  28.  
  29. int CEntity::get_y()
  30. {
  31. return y;
  32. }
  33.  
  34. int CEntity::get_hight()
  35. {
  36. return hight;
  37. }
  38.  
  39. int CEntity::get_width()
  40. {
  41. return width;
  42. }
  43.  
  44. char CEntity::get_file()
  45. {
  46. return *file;
  47. }
  48.  
  49.  
  50. //Dona erroer es te que mirar, tot i que per el moment no es necessari mes endevant pot ser que ho necessitem
  51. /*SDL_Renderer CEntity::get_window() {
  52. return window;
  53. }*/
  54.  
  55. void CEntity::set_x(int x)
  56. {
  57. this->x = x;
  58. }
  59.  
  60. void CEntity::set_y(int y)
  61. {
  62. this->y = y;
  63. }
  64.  
  65. void CEntity::set_hight(int hight)
  66. {
  67. this->hight = hight;
  68. }
  69.  
  70. void CEntity::set_width(int width)
  71. {
  72. this->width = width;
  73. }
  74.  
  75. void CEntity::set_file(char* file) {
  76. this->file = file;
  77. }
  78.  
  79. void CEntity::set_window(SDL_Renderer* window) {
  80. this->window = window;
  81. }
  82.  
  83. void CEntity::load()
  84. {
  85. //Carga la imagen del pj
  86. image = Sprite::Load(file, window);
  87. }
  88.  
  89. void CEntity::draw()
  90. {
  91. //Dibuja el pj
  92. Sprite::Draw(window, image, x, y, width, hight);
  93. }
  94.  

Entity.h
Código
  1. #pragma once
  2. #include <SDL.h>
  3. class CEntity
  4. {
  5. public:
  6. CEntity();
  7. CEntity(char * file, int x, int y, int hight, int width, SDL_Renderer* window);
  8. ~CEntity();
  9. int get_x();
  10. int get_y();
  11. int get_hight();
  12. int get_width();
  13. SDL_Renderer get_window();
  14. char get_file();
  15. void set_file(char* file);
  16. void set_window(SDL_Renderer*  Window);
  17. void set_x(int x);
  18. void set_y(int y);
  19. void set_hight(int hight);
  20. void set_width(int width);
  21.  
  22. virtual void move() = 0;
  23. void load();
  24. void draw();
  25.  
  26. private:
  27. SDL_Renderer* window;
  28. SDL_Texture* image;
  29. char* file;
  30.  
  31. protected:
  32. int hight;
  33. int width;
  34. int x;
  35. int y;
  36.  
  37. };
  38.  

Player.cpp
Código
  1. #include "Player.h"
  2. #include "Entity.h"
  3.  
  4. CPlayer::CPlayer(char * file, int x, int y, int hight, int width, SDL_Renderer * window) : CEntity(file, x, y, hight, width, window)
  5. {
  6.  
  7. }
  8. CPlayer::CPlayer()
  9. {
  10. }
  11. void CPlayer::movee(SDL_Event evento) {
  12. switch (evento.key.keysym.sym) {
  13.  
  14. //Eventos de teclado depende del que se clique un movimiento o otro
  15. case SDLK_UP:
  16. if (y > 0)
  17. //Se resta la posicion y
  18. y = y - 10;
  19.  
  20. break;
  21. case SDLK_DOWN:
  22. if (y < 340)
  23. //Se suma la posicion y
  24. y = y + 10;
  25.  
  26. break;
  27. case SDLK_LEFT:
  28. //Se resta la posicion x
  29. if (x > 0)
  30. x = x - 10;
  31.  
  32. break;
  33. case SDLK_RIGHT:
  34. //Se resta la posicion y
  35. if (x < 540)
  36. x = x + 10;
  37. break;
  38. }
  39. }
  40.  
  41. void CPlayer::move()
  42. {
  43. }
  44.  

Player.h
Código
  1. #pragma once
  2. #include<SDL.h>
  3. #include"Sprite.h"
  4. #include "Entity.h"
  5. class CPlayer : public CEntity
  6. {
  7. public:
  8. CPlayer(char * file, int x, int y, int hight, int width, SDL_Renderer* window);
  9. CPlayer();
  10. void movee(SDL_Event evento);
  11. void move();
  12.  
  13. private:
  14. };

PlayState.cpp
Código
  1. #include <stdio.h>
  2.  
  3. #include "SDL.h"
  4. #include "Game.h"
  5. #include "PlayState.h"
  6. #include "PauseState.h"
  7. #include "Player.h"
  8.  
  9. PlayState PlayState::m_PlayState;
  10.  
  11. void PlayState::Init(Game* game)
  12. {
  13. playSprite = NULL;
  14.  
  15. playSprite = Sprite::Load("sprites/playstate.bmp", game->GetRenderer());
  16.  
  17. //Constructor del jugador, se passa la ubicacion de la imagen i sus datos igual que
  18. //el renderer donde se carga
  19. player = CPlayer("sprites/macaco.bmp", 200, 200, 64, 64, game->GetRenderer());
  20. //Defino la posicion inicial del enemigo
  21.  
  22. enemy_x = posicions_x[0];
  23. enemy_y = posicions_y[0];
  24. //Cargo la imagen del enemigo
  25. enemy = Sprite::Load("sprites/crab.bmp", game->GetRenderer());
  26.  
  27. //Cargo la imagen del jugador
  28. player.load();
  29.  
  30. printf("PlayState Init Successful\n");
  31. }
  32.  
  33. void PlayState::Clean()
  34. {
  35. printf("PlayState Clean Successful\n");
  36. }
  37.  
  38. void PlayState::Pause()
  39. {
  40. printf("PlayState Paused\n");
  41. }
  42.  
  43. void PlayState::Resume()
  44. {
  45. printf("PlayState Resumed\n");
  46. }
  47.  
  48. void PlayState::HandleEvents(Game* game)
  49. {
  50. SDL_Event event;
  51.  
  52. if (SDL_PollEvent(&event)) {
  53. switch (event.type) {
  54. case SDL_QUIT:
  55. game->Quit();
  56. break;
  57.  
  58. case SDL_KEYDOWN:
  59. switch (event.key.keysym.sym) {
  60.  
  61. //Eventos de teclado depende del que se clique un movimiento o otro
  62. case SDLK_SPACE:
  63. game->PushState(PauseState::Instance());
  64. break;
  65. }
  66. player.movee(event);
  67.  
  68.  
  69. //Comproba el contador per el seguiment del enemic
  70. if (cont < 8) {
  71. //Guarda les posicions anterior del pj a les cordenades del enemic
  72. enemy_x = posicions_x[cont];
  73. enemy_y = posicions_y[cont];
  74. //Esborra les cordenades utilitzades ara i les actualitza amb les actuals
  75. posicions_x[cont] = player.get_x();
  76. posicions_y[cont] = player.get_y();
  77. //Suma el contador
  78. cont++;
  79. }
  80.  
  81. else
  82. {
  83. //El contador arriba al maxim i es torna a possar a 0
  84. cont = 0;
  85. }
  86. }
  87. }
  88.  
  89. }
  90.  
  91. void PlayState::Update(Game* game)
  92. {
  93. }
  94.  
  95. void PlayState::Draw(Game* game)
  96. {
  97. Sprite::DrawFullScreen(game->GetRenderer(), playSprite);
  98. //Dibuja el enemigo
  99. Sprite::Draw(game->GetRenderer(), enemy, enemy_x, enemy_y, 64, 64);
  100. //Dibuja el personaje
  101. player.draw();
  102. SDL_RenderPresent(game->GetRenderer());
  103. }

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!
;-) >:D ;-) >:D :laugh: :rolleyes:
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.
Código
  1. package xor;
  2.  
  3. import java.io.FileReader;
  4. import java.io.FileWriter;
  5. import java.util.Scanner;
  6.  
  7. public class XOR {
  8.  
  9.    public static void main(String[] args) {
  10.        try
  11.        {
  12.            System.out.println("Introdueix el nom de l'arxiu: ");
  13.            String nomArxiu = new Scanner(System.in).nextLine();
  14.            System.out.println("Introdueix el nom de l'arxiu encriptat: ");
  15.            String nomArxiu2 = new Scanner(System.in).nextLine();
  16.            System.out.println("Introdueix la contrasenya de encriptació: ");
  17.            String password = new Scanner(System.in).nextLine();
  18.            int tamaño = password.length();
  19.            int cont = 0;
  20.            if (!nomArxiu.equals(nomArxiu2))
  21.            {
  22.                FileReader fr = new FileReader("arxius\\" + nomArxiu);
  23.                FileWriter fw = new FileWriter("arxius\\" + nomArxiu2);
  24.                int caracter = fr.read();
  25.                while(caracter != -1)
  26.                {
  27.                    int encrip = caracter ^ password.charAt(cont); //cifra la letra
  28.                    fw.write(encrip); //escribe la letra en el fichero
  29.                    caracter = fr.read(); //lee el siguiente caracter
  30.                 if (cont  < tamaño - 1)
  31.                 {
  32.                     cont++;
  33.                 }
  34.                 else
  35.                 {
  36.                     cont = 0;
  37.                 }
  38.                }
  39.                fr.close();
  40.                fw.close();
  41.            }
  42.        }
  43.        catch (Exception e)
  44.        {
  45.            System.out.println("e.toString");
  46.        }
  47.    }
  48.  
  49. }
  50.  

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:
Código
  1. #include <stdio.h>
  2. #include <windows.h>
  3. #include <conio.h>
  4. #include <stdlib.h>
  5. #include <list>
  6. using namespace std;
  7. #define ARRIBA 72
  8. #define IZQUIERDA 75
  9. #define DERECHA 77
  10. #define ABAJO 80
  11.  
  12. void fflush_in() {
  13. int ch;
  14. while ((ch = fgetc(stdin)) != EOF && ch != '\n') {}
  15. }
  16.  
  17. void gotoxy(int x, int y) {
  18. //HANDLE es el nombre que recibe la consola, i l'he ponemos el nombre de que queramos
  19. //en este caso hCon que es el que se pone por defecto.
  20. HANDLE hCon;
  21. //Coje el identificador de la ventana (GetStdHandle)
  22. hCon = GetStdHandle(STD_OUTPUT_HANDLE);
  23. //Creamos las cordenadas.
  24. COORD dwPos;
  25. dwPos.X = x;
  26. dwPos.Y = y;
  27. SetConsoleCursorPosition(hCon, dwPos);
  28. }
  29. void ocultarCursor() {
  30. HANDLE hCon;
  31. hCon = GetStdHandle(STD_OUTPUT_HANDLE);
  32. CONSOLE_CURSOR_INFO cci;
  33. cci.dwSize = 2;
  34. cci.bVisible = FALSE;
  35. SetConsoleCursorInfo(hCon, &cci);
  36. }
  37. void pintarLimites() {
  38. for (int i = 2; i < 78; i++) {
  39. gotoxy(i, 3); printf("%c", 205);
  40. gotoxy(i, 33); printf("%c", 205);
  41. }
  42. for (int i = 4; i < 33; i++) {
  43. gotoxy(2, i); printf("%c", 186);
  44. gotoxy(77, i); printf("%c", 186);
  45. }
  46. gotoxy(2, 3); printf("%c", 201);
  47. gotoxy(2, 33); printf("%c", 200);
  48. gotoxy(77, 3); printf("%c", 187);
  49. gotoxy(77, 33); printf("%c", 188);
  50. }
  51.  
  52. class NAVE {
  53. int x, y;
  54. int corazones;
  55. int vidas;
  56. public:
  57. NAVE(int _x, int _y, int _corazones, int _vidas) : x(_x), y(_y), corazones(_corazones), vidas(_vidas) {}
  58. int X() { return x; }
  59. int Y() { return y; }
  60. int VID() { return vidas; }
  61. void pCorazon() { corazones--; }
  62. void gCorazon() { if (corazones < 3)corazones++; }
  63. void pintar();
  64. void borrar();
  65. void mover();
  66. void pintarCorazones();
  67. void morir();
  68. };
  69. class AST {
  70. int x, y;
  71. public:
  72. AST(int _x, int _y) : x(_x), y(_y) {}
  73. void pintar();
  74. void mover();
  75. void choque(class NAVE &N);
  76. void borrar();
  77. int X() { return x; }
  78. int Y() { return y; }
  79. };
  80. class VIDA {
  81. int x, y;
  82. public:
  83. VIDA(int _x, int _y) : x(_x), y(_y) {}
  84. void pintar();
  85. void mover();
  86. void choque(class NAVE &N);
  87. void borrar();
  88. };
  89. class BALA {
  90. int x, y;
  91. public:
  92. BALA(int _x, int _y) : x(_x), y(_y) {};
  93. int X() { return x; }
  94. int Y() { return y; }
  95. void mover();
  96. bool fuera();
  97. };
  98. /*
  99. ALTERNATIVA a : x(_x), y(_y) {}
  100. NAVE::NAVE(int _x, int _y) {
  101. x = _x;
  102. y = _y;
  103. }*/
  104. void NAVE::pintar() {
  105. gotoxy(x, y); printf(" %c", 30);
  106. gotoxy(x, y + 1); printf(" %c%c%c", 40, 207, 41);
  107. gotoxy(x, y + 2); printf("%c%c %c%c", 30, 190, 190, 30);
  108. system("color 7");
  109. }
  110.  
  111. void NAVE::borrar() {
  112. gotoxy(x, y); printf(" ");
  113. gotoxy(x, y + 1); printf(" ");
  114. gotoxy(x, y + 2); printf(" ");
  115. }
  116.  
  117. void NAVE::mover() {
  118.  
  119. if (kbhit()) {
  120. char tecla = getch();
  121. borrar();
  122. if (tecla == IZQUIERDA && x > 3) x--;
  123. if (tecla == DERECHA && x + 6 < 77) x++;
  124. if (tecla == ARRIBA && y > 4) y--;
  125. if (tecla == ABAJO && y + 3 < 33) y++;
  126. pintar();
  127. pintarCorazones();
  128. }
  129. }
  130. void NAVE::pintarCorazones() {
  131.  
  132. gotoxy(50, 2); printf("VIDAS %d", vidas);
  133. gotoxy(64, 2); printf("Salud");
  134. gotoxy(70, 2); printf(" ");
  135. for (int i = 0; i < corazones; i++) {
  136. gotoxy(70 + i, 2); printf("%c\r", 03);
  137. }
  138. }
  139. void NAVE::morir() {
  140. if (corazones == 0) {
  141. borrar();
  142. gotoxy(x, y); printf(" * ");
  143. gotoxy(x, y + 1); printf("** **");
  144. gotoxy(x, y + 2); printf(" * ");
  145. Sleep(200);
  146. borrar();
  147. gotoxy(x, y); printf("* * *");
  148. gotoxy(x, y + 1); printf(" * ");
  149. gotoxy(x, y + 2); printf("* * *");
  150. Sleep(200);
  151. borrar();
  152. vidas--;
  153. corazones = 3;
  154. pintarCorazones();
  155. pintar();
  156. }
  157.  
  158.  
  159.  
  160.  
  161. }
  162. void AST::pintar() {
  163. gotoxy(x, y); printf("%c", 'o');
  164. }
  165. void AST::mover() {
  166. gotoxy(x, y); printf(" ");
  167. y++;
  168. if (y > 32) {
  169. x = rand() % 71 + 4;
  170. y = 4;
  171. }
  172. pintar();
  173. }
  174. void AST::choque(class NAVE &N) {
  175. if (x >= N.X() && x < N.X() + 6 && y >= N.Y() && y <= N.Y() + 2) {
  176. N.pCorazon();
  177. borrar();
  178. N.pintar();
  179. N.pintarCorazones();
  180. x = rand() % 71 + 4;
  181. y = 4;
  182. }
  183. }
  184.  
  185. void AST::borrar() {
  186. gotoxy(x, y); printf(" ");
  187. }
  188.  
  189. void VIDA::pintar() {
  190. gotoxy(x, y); printf("%c", 3);
  191. }
  192. void VIDA::mover() {
  193. gotoxy(x, y); printf(" ");
  194. y++;
  195. if (y > 32) {
  196. x = rand() % 71 + 4;
  197. y = 4;
  198. }
  199. pintar();
  200. }
  201. void VIDA::choque(class NAVE &N) {
  202. if (x >= N.X() && x < N.X() + 6 && y >= N.Y() && y <= N.Y() + 2) {
  203. N.gCorazon();
  204. N.pintarCorazones();
  205. borrar();
  206. N.pintar();
  207. x = rand() % 71 + 4;
  208. y = 4;
  209. }
  210. }
  211. void VIDA::borrar() {
  212. gotoxy(x, y); printf(" ");
  213. }
  214. void BALA::mover() {
  215. gotoxy(x, y); printf(" ");
  216. y--;
  217. gotoxy(x, y); printf("*");
  218. }
  219. bool BALA::fuera() {
  220. if (y == 4) {
  221. return true;
  222. }
  223. else {
  224. return false;
  225. }
  226. }
  227. int main() {
  228. char tecla;
  229. do
  230. {
  231. ocultarCursor();
  232. pintarLimites();
  233. list<AST*> A;
  234. list<AST*>::iterator itA;
  235. for (int i = 0; i < 5; i++) {
  236. A.push_back(new AST(rand() % 75 + 3, rand() % 5 + 4));
  237. }
  238. NAVE N(15, 25, 3, 3);
  239. VIDA vit(15, 8);
  240. list<BALA*> B;
  241. list<BALA*>::iterator it;
  242. N.pintar();
  243. int puntos = 0;
  244. bool game_over = false;
  245. while (!game_over) {
  246. gotoxy(4, 2); printf("PUNTOS %d", puntos);
  247. if (kbhit()) {
  248. char tecla = getch();
  249. if (tecla == 'a') {
  250. B.push_back(new BALA(N.X() + 2, N.Y() - 1));
  251. }
  252. }
  253. for (it = B.begin(); it != B.end();) {
  254. (*it)->mover();
  255. if ((*it)->fuera()) {
  256. gotoxy((*it)>X(), (*it)>Y()); printf(" ");
  257. delete(*it);
  258. it = B.erase(it);
  259. }
  260. else { it++; }
  261. }
  262. N.mover();
  263. vit.mover(); vit.choque(N);
  264. for (itA = A.begin(); itA != A.end(); itA++) {
  265. (*itA)->mover();
  266. (*itA)->choque(N);
  267. }
  268. for (itA = A.begin(); itA != A.end(); itA++) {
  269. for (it = B.begin(); it != B.end();) {
  270. if ((*itA)>X() == (*it)>X() && ((*itA)>Y() + 1 == (*it)>Y() || (*itA)>Y() == (*it)>Y())) {
  271. gotoxy((*it)>X(), (*it)>Y()); printf(" ");
  272. delete (*it);
  273. it = B.erase(it);
  274. A.push_back(new AST(rand() % 74 + 3, 4));
  275. gotoxy((*itA)>X(), (*itA)>Y()); printf(" ");
  276. delete (*itA);
  277. itA = A.erase(itA);
  278. puntos = puntos + 5;
  279. }
  280. else { it++; }
  281.  
  282. }
  283. }
  284. if (N.VID() < 0)
  285. {
  286. game_over = true;
  287. }
  288. N.morir();
  289. Sleep(60);
  290. }
  291. gotoxy(4, 35); printf("\nGAME OVER\n");
  292. printf("JUGAR DE 9? [S/N]\n");
  293. do {
  294. scanf("%c", &tecla);
  295. fflush_in();
  296. tecla = towlower(tecla);
  297. if (tecla != 's' && tecla != 'n') {
  298. printf("Solo [S/N]");
  299. }
  300. } while (tecla != 's' && tecla != 'n');
  301. system("cls");
  302. } while (tecla != 'n');
  303. return 0;
  304. }&#65279;
5  Informática / Hardware / No me detecta el disco duro. en: 12 Marzo 2016, 13:21 pm
Buenas, he tenido el siguiente problema, en cuando conecto el disco duro en el ordenador, no me sale como dispositivos en mi equipo, pero si que lo detecta en administrador de dispositivos. he intentado desinstalando driver y volviendo a instalar pero nada, también he probado en asignarle una nueva letra en el disco, pero tampoco me deja, lo he probado des del diskpart donde me detecta el disco pero no como volumen y no puedo asignarle ninguna letra... Si a alguien li ha passado lo mismo o sabe alguna solución me gustaría que me la pudiese facilitar. Muchas gracias, un saludo. ::) ::) ::) ::) :silbar: :silbar:
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:

Código
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #include <ctype.h>
  5.  
  6. void main() {
  7. srand(time(NULL));
  8. int r, res, i;
  9. bool exit = false, ok;
  10. char retry;
  11. printf("JOC DE ENDEVINAR EL NUMERO\n\n");
  12. do {
  13. r = (rand() % 10) + 1;
  14. i = 0;
  15. do{
  16. printf("Introdueix un numero (1-10): ");
  17. /*-------------------------------------------*/
  18. /*-------------------------------------------*/
  19. /*-------------------------------------------*/
  20. ok = scanf("%i", &res);
  21. /*-------------------------------------------*/
  22. /*-------------------------------------------*/
  23. /*-------------------------------------------*/
  24. while (getchar() != '\n');
  25. if (ok && res >= 1 && res <= 10 ) {
  26. if (res < r)
  27. {
  28. printf("Nº massa baix\n");
  29. }
  30. else if (res > r) {
  31. printf("Nº massa alt\n");
  32. }
  33. else if (res == r) {
  34. printf("Has encertat!\n");
  35. exit = true;
  36. }
  37. i++;
  38. }
  39. else
  40. {
  41. printf("No has introduit un valor disponible\n");
  42. }
  43. }while (i < 12 && exit == false );
  44. printf("Intents realitzats: %d\n", i);
  45. exit = false;
  46. do{
  47. printf("Vols tornar a jugar? (Y/N): ");
  48. scanf("%c", &retry);
  49. retry = towlower(retry);
  50. while (getchar() != '\n');
  51. if (retry == 'n')
  52. {
  53. exit = true;
  54. }
  55. else if (retry == 'y')
  56. {
  57.  
  58. }
  59. else
  60. {
  61. printf("Introdueix una opcioo vàlida\n");
  62. }
  63. }while (retry != 'y' && retry != 'n');
  64. } while (exit == false);
  65. system("pause");
  66. }


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.
Código
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. void main() {
  5. int hores, preu, total;
  6. printf("Quantes hores has fet a la setmana? ");
  7. scanf("%d", &hores);
  8. printf("Quant cobres per hora");
  9. scanf("%d", preu);
  10. if (hores <= 40) {
  11. total = hores*preu;
  12. printf("El sou teu és de %d euros a la setmana\n", total);
  13. }
  14. else if (hores <= 48) {
  15. total = (40 * preu) + ((hores - 40)*preu * 2);
  16. printf("El teu sou és de %d euros a la setmana\n", total);
  17. }
  18. else if (hores > 48) {
  19. (total = 40 * preu) + ((hores - 40)*preu * 2) + ((hores - 48)*preu * 2);
  20. printf("El teu sou és de %d euros a la setmana\n", total);
  21. }
  22. }
8  Programación / Programación C/C++ / El Visual Studio me ignora el fflush(stdin). en: 29 Octubre 2015, 11:30 am
Pues como dice no me funciona el fflush para vaciar el buffer del teclado. He buscado alterantivas como esta:
Código
  1. while(getchar()!='\n');
.Pero me gustaria Saber porque no me fuciona y poder encontrar la solución. Por si es necesario uso WIndows 10. Un saludo.
Páginas: [1]
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines