Introducción a C++

1

Todo lo que aprenderás sobre C++

2

¿Qué es programar y por qué aprender C++?

Conceptos Generales de C++

3

La Historia de C++ y sus diferencias con C

Preparando el entorno de trabajo

4

Instalando Codeblocks

5

Pasos para instalar en mac

6

Ejecutando nuestro primer programa

7

¿Qué son las librerías STD? - Portada del Proyecto

Manejo de memoria

8

¿Qué es la memoria y tipos de datos?

9

Alojando variables en memoria

10

¿Cómo usar operadores?

11

¿Qué son los apuntadores?

12

Reto: Escribir un programa que calcule áreas.

Entrada de datos y funciones

13

¿Cómo introducir datos a nuestro programa?

14

¿Cómo usar condicionales?

15

Usando condicionales

16

¿Cómo encapsular código en funciones ?

17

¿Qué son los parámetros y como usarlos?

18

Reto: Juego narrativo implementando condicionales y entrada de datos.

Loops y arreglos

19

¿Qué son los arreglos?

20

¿Qué son los Loops?

21

Programando Loops

22

Loops , arreglos y arreglos bidimensionales

23

Dibujando el mapa de nuestro juego con arreglos

24

Manipulando mi jugador con inputs en arreglos unidimensionales

25

Arreglos bidimensionales

26

Reto: Moviendo a mi personaje en mi arreglo bidimensional

Lectura de Archivos

27

Creando y leyendo un archivo externo

28

Leyendo archivos externos

29

Reto: En el mapa, crear punto de inicio y salida del jugador

Programación Orientada a Objetos

30

¿Qué es POO?

31

Definiendo una clase y creando sus instancias

32

Encapsulación

33

Abstracción

34

Herencia

35

Propiedades de clase en herencia

36

Polimorfismo

Finalizando nuestro proyecto

37

Creación de personaje y archivo de encabezado

38

Moviendo mi personaje con entrada de datos

39

Mapa

40

Interacción entre el personaje y el mapa

41

Paredes

42

Optimizando trazado de mapa

43

Colisiones

44

Creando nuestra portada de juego

45

Tesoro y victoria

46

Conclusiones

47

Proyecto final

You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
3 Hrs
43 Min
15 Seg

Dibujando el mapa de nuestro juego con arreglos

23/47
Resources

We are going to create a variable with the position of our character and another one with an array of its possible positions. The purpose of this is that we can create a for loop and draw our world and indicate where our character is.

For now we can only move left and right but later we are going to program a more complicated map.

Contributions 29

Questions 1

Sort by:

Want to see more contributions, questions and answers from the community?

Así va mi versión del juego hasta ahora usando todo lo que hemos aprendido en clase (switchs, do whiles, condicionales, entre otras): https://repl.it/repls/PeriodicMushyNasm

Código:

#include <iostream>

void draw_world(int lives, char map[3], int heroPos) {
  std::cout << "\n\n";

  std::cout << "Vidas: " << lives << "\n";
  
  // Imprime H en la posicion del personaje
  // y - en cualquier otra parte.
  for (int i = 0; i < 3; i++) {
    if (i == heroPos) {
      std::cout << "H";
    } else {
      std::cout << map[i];
    }
  }

  std::cout << "\n\n";
}

char ask_move() {
  char lastMove;
  
  std::cout << "Izquierda o derecha (i/d): ";
  std::cin >> lastMove;

  return lastMove;
}

int main() {
  std::cout << "Hello World!\n\n";

  char map[3] = {'-', '-', '-'};
  int heroPos = 0;
  char lastMove = ' ';
  int lives = 5;

  do {
    draw_world(lives, map, heroPos);

    char move = ask_move();

    switch (move) {
      case 'i':
        if ((heroPos - 1) < 0) {
          std::cout << "NO TE PUEDES SALIR DEL MAPA";
          lives--;
        } else {
          heroPos--;
        }
      break;
      case 'd':
        if ((heroPos + 1) > 2) {
          std::cout << "NO TE PUEDES SALIR DEL MAPA";
          lives--;
        } else {
          heroPos++;
        }
      break;
      default: std::cout << "Vuelve a intentarlo.";
      break;
    }
  } while (lives > 0);

  std::cout << "\nGAME OVER!\n";
}

Repitiendo el código y después de varios errores ya funciono 😃

using namespace std;

void DrawMap (int HeroPos, char GameMap [5]){
    for (int i = 0; i < 5; i++){
        if (i != HeroPos){
            cout << GameMap[i];
        }
        else {
            cout << 'H';
        }
    }
}

int main()
{
    char GameMap [5]= {'1','1','1','1','1'};
    int HeroPos = 0;
    DrawMap (HeroPos, GameMap);

    return 0;
}

Hecho!!

util para proyectos

Hice el mismo juego que el profesor, pero con la diferencia de que le agregue la opcion de poder desplazarse, sin que se cayera el array.

#include <iostream>

using namespace std;

void GameMap(char MapGame[5],int HeroPosition){
    
    for (int i = 0; i < 5; i++)
    {
        if (HeroPosition != i){
            cout << MapGame[i] << " ";
        }else{
            cout << "X"<< " ";
        }
    }
    cout << endl;
}

int MoveHero(int HeroPosition){
    cout << "Digite la dirección a la que se desea mover: (d = derecha)(a = izquierda) ";
    char move;
    cin >> move;

    switch (move)
    {
    case 'a':
        if (HeroPosition != 0){
        HeroPosition -= 1;
        }else
        {
            cout << "No se puede desplazar a la Izquierda porque el camino llega hasta ahí."<< endl;
            HeroPosition = HeroPosition;
        }
        return HeroPosition;
        break;

    case 'd':
        if (HeroPosition < 4){
            HeroPosition += 1;
        }else{
            cout  << "No se puede desplazar a la Derecha porque el camino llega hasta ahí."<< endl;
            HeroPosition = HeroPosition;
        }
        return HeroPosition;

    default:
        HeroPosition = HeroPosition;
        break;
    }
    return HeroPosition;
}

int main()
{

    char MapGame[5] = {'1','1','1','1','1'};
    int HeroPosition = 0;
    string seguir = "si";

    GameMap(MapGame,HeroPosition);

    do{
    HeroPosition = MoveHero(HeroPosition);
    cout << "Su nueva posicion: " << endl;
    GameMap(MapGame,HeroPosition);

    cout << "Desea seguir Jugando ?? (si para continuar / cualquier otra tecla para salirse) ";
    cin >> seguir;
    } while (seguir == "si");


    return 0;
}```

Aca tambien dividi un poco el programa, una funcion para dibujar y la otra para llenar el mapa

#include <iostream>
#include <array>

using namespace std;

void drawMap(char gameMap[]) {
    int mapSize = sizeof(gameMap);
    for ( int i = 0; i < mapSize; i++ ) {
        cout << gameMap[i] << "";
    }
}

void fillMap( int player, char gameMap[] ) {
    const char EMPTY = '1';

    int mapSize = sizeof(gameMap);

    for ( int i = 0; i < mapSize; i++ ) {
        if ( i == player ) {
            gameMap[i] = 'H';
        }
        else {
            gameMap[i] = EMPTY;
        }

    }
}

int main() {

    char gameMap[5];
    int heroPos = 1;

    fillMap( heroPos, gameMap );
    drawMap( gameMap );

    return 0;
}

Hice una implementación parecida, agregando que el jugador se puede mover hacia arriba y abajo, además al “salir” por los bordes aparece al otro lado del mapa. De igual forma, se puede variar el tamaño del mapa por medio de dos variables.

// ------------------------Controles del juego------------------------
// Izquierda → "a" Derecha → "d" Arriba → "w" Abajo → "s" Salir → "x"

#include <iostream>
#include <conio.h>

using namespace std;

struct player_pos{
        int x = 0;
        int y = 0;
    };

// Altura y largo del mapa
const int length = 6, height = 3;

void dibujar_mapa(player_pos new_player_pos, player_pos last_player_pos, char map[height][length], int map_length, int map_height){ // Genera el mapa
    
    // Coloca al jugador en el mapa
    map[last_player_pos.y][last_player_pos.x] = '_';
    map[new_player_pos.y][new_player_pos.x] = '*';
    
    // Dibuja el mapa
    system("cls");
    //cout << "X: " << new_player_pos.x << " Y: " << new_player_pos.y <<endl;
    for (int c = 0; c <  map_height; c++){
        for(int i = 0; i < map_length; i++){
            cout << map[c][i];
        }
        cout << endl;
    }
    cout << endl << endl;
}

player_pos movimiento(player_pos last_player_pos, int map_length, int map_height){ // Movimiento del jugador
    char instruccion;
    player_pos new_player_pos;
    new_player_pos.x = last_player_pos.x;
    new_player_pos.y = last_player_pos.y;

    // Recibe la instrucción del teclado
    instruccion = getch();
    
    // Verifica la instrucción de entrada para moverse 
    // Izquierda → "a" Derecha → "d" Arriba → "w" Abajo → "s" Salir → "x"
    switch (instruccion)
    {
    case 'a': // Mover izquierda
        if (last_player_pos.x <= 0){
            // Condición por si desborda por la izquierda
            new_player_pos.x = map_length - 1;
            return new_player_pos;
        }
        new_player_pos.x = last_player_pos.x - 1;
        return new_player_pos;
        break;

    case 'd': // Mover derecha
        if (last_player_pos.x >= map_length - 1){
            // Condición por si desborda por la derecha
            new_player_pos.x = 0;
            return new_player_pos;
        }
        new_player_pos.x = last_player_pos.x + 1;
        return new_player_pos;
        break;

    case 'w': // Mover arriba
        if (last_player_pos.y <= 0){
            // Condición por si desborda por arriba
            new_player_pos.y = map_height - 1;
            return new_player_pos;
        }
        new_player_pos.y = last_player_pos.y - 1;
        return new_player_pos;
        break;
    
    case 's': // Mover abajo
        if (last_player_pos.y >= map_height - 1){
            // Condición por si desborda por abajo
            new_player_pos.y = 0;
            return new_player_pos;
        }
        new_player_pos.y = last_player_pos.y + 1;
        return new_player_pos;
        break;
    
    case 'x': // Salir
        new_player_pos.x = map_length + 1;
        return new_player_pos;

    default:
        // Condición si presiona cualquier otra tecla
        return new_player_pos;
        break;
    }
}

int main(){
    
    // Se genera el mapa
    char map[height][length];
    for (int c = 0; c <  height; c++){
        for(int i = 0; i < length; i++){
            map[c][i] = '_';
        }
    }

    player_pos player_pos, last_player_pos;
    last_player_pos.x = 1;
    last_player_pos.y = 1;

    cout << "X: " << player_pos.x << " Y: " << player_pos.y <<endl;

    while(player_pos.x <= length){
        dibujar_mapa(player_pos, last_player_pos, map, length, height);
        last_player_pos = player_pos;
        player_pos = movimiento(player_pos, length, height);
    }
}

En c++ no hay scoope?

Cool

Se puede utilizar continue para evitar else

Gracias por la clase.

#include <iostream>

using namespace std;


void DrawMap(int HeroPos, char GameMap[5])
{
    for(int i = 0; i < 5; i++)
    {
        if(i != HeroPos)
        {
            cout << GameMap[i];
        }
        else
        {
            cout << "H";
        }
    }

}



int main()
{
    int HeroPos = 1;
    char GameMap[5] = {'1','1','1','1','1'};

    DrawMap(HeroPos, GameMap);

    return 0;
}```

HECHO ;D


#include <iostream>

using namespace std;

/*HeroPos no existe dentro de la funcion drawmap
por lo tanto se tiene que pasar como parametro al igual que map

*/
void drawmap(int HeroPos, char map[5])
{

  for(int i = 0; i < 5; i++)
    {
        if(i != HeroPos)
        {
         cout<<map[i];
        }
            else
           {
               cout<<'H';
           }

    }
}
int main()
{
    char HeroPos = 4;
    char map[5]={'1','1','1','1','1'};

    drawmap(HeroPos,map);

    return 0;
}

Rombo perfecto

#include <iostream>

using namespace std;
int main(){
  char num[5]={' ',' ',' ',' ',' '};
  int i;
  for(i=0;i<9;i++){
    cout<<i<<' ';
    if(i>=5){
      num[i-5]=' ';  
    } 
    else{
      num[4-i]='|';  
    }
    for(int j=0;j<5;j++){
      cout<<num[j];  
    }

    for(int j=3;j>=0;j--){
      cout<<num[j];  
    }
    cout<<' '<<i;
    cout<<endl;
  }

}


#include <iostream>

using namespace std;
int main(){
  char num[5]={' ',' ',' ',' ','|'};
  int c=0;
  for(int i=0;i<5;i++){
    num[4-c]='|';
    for(int j=0;j<5;j++){
      cout<<num[j];  
    }
    cout<<endl;
    c++;
  }

}```

¿Está bien decir que lo que ponemos entre paréntesis, en la función DrawMap, es el método constructor?

#include <iostream>
using namespace std;

const int MAP_ARRAY_LEN = 5;

void DrawMap (const int& heroPos, const char GameMap[]) 
{
    for (int i = 0; i < MAP_ARRAY_LEN; i++)
    {
        if (i != heroPos)
            cout << GameMap[i];
        else
            cout << 'H';
    }
    cout << endl;
}

int main ()
{
    int heroPos = 1;
    char GameMap[MAP_ARRAY_LEN] = {'1','1','1','1','1'};

    DrawMap(heroPos,GameMap);

    return 0;
}
#include <iostream> //libreria de entrada y salida

using namespace std; // permite usar con facilidad cout cin
void DrawMap(int HeroPos, char Gamemap[5]) //creamos la funcion dibujar mapa donde LLAMAMOS a los PARAMETROS que estan en la funcion principal
{
  for (int i = 0 ; i<5; i ++ ) 
     {
         if(i!= HeroPos)
         {
           cout<<Gamemap[i];
         }
         else
         {
             cout<< 'H';
         }


     }
}
int main()//funcion principal donde nuestro programa empieza a correr
{
    int HeroPos=0;//posicion actual de mi personaje
    char Gamemap [5] = {'1','1','1','1','1'}; // en que poscion del mapa estara el jugador
     DrawMap(HeroPos,Gamemap); // llamamos a los parametros para leerlos

    return 0;
}

esta muy vacano este curso. los felicito

#include <iostream>

using namespace std;

void DrawHeroMap(int heroPos, char  Map[5])
{
    for(int i=0;i<5;i++)
    {
        if(i !=heroPos){
            cout<<Map[i];
        }else{
            cout<<'H';
        }
    }

}
int main()
{
    int heroPos= 4;
    char Map[5]={'[', '[', '[', '[', '['};

    DrawHeroMap(heroPos, Map);

    return 0;
}

Megustaría agregar que en la definición de a función

void drawMap(int heroPos, char gameMap[5];

El nombre que se le da a los parametros y el nombre de la variable que se va usar como parametro
En el ejercicio era:

int heroPos = 1;
char gameMap[5] = {'1', '1', '1', '1', '1'};

pueden ser diferente
Ejemplo utilizando el progrma usado en la lección

#include <iostream>
using namespace std;


void drawMap(int heroPos, char gameMap[5]){

    for(int i = 0; i < 5; i++){
        
        if(i != heroPos)
            cout << gameMap[i];
        else
            cout << "H";
       
    }
    cout << endl;

}

int main()
{
    int position = 1;
    char map[5] = {'1','1','1','1','1'};

    drawMap(position, map);
    return 0;
}

Pueden correrlo en su equipo para comprobarlo : D

Codigo de la clase:

<#include<iostream>
using namespace std;
void DrawMap(int HeroPos, char Gamemap[5])
{
  for (int i = 0 ; i<5; i ++ )
     {
         if(i!= HeroPos)
         {
           cout<<Gamemap[i];
         }
         else
         {
             cout<< 'H';
         }
     }
}
int main()r
{
    int HeroPos=0;
    char Gamemap [5] = {'1','1','1','1','1'};
     DrawMap(HeroPos,Gamemap);
    return 0;
}
>

Bien!

El código y algo más

#include <iostream>

using namespace std;

void DrawMap(int HeroPos, char GameMap[5])//Le paso las variables por parametro, en este caso las posicion y el mapa
{
    for(int i = 0; i < 5; i++)
    {
        if(i != HeroPos)
        {
            cout << GameMap[i];// Si la posición del jugador es distinta a la casilla que esta iterando en i entonces se dibuja mapa
        }
        else
        {
            cout << 'H';// Si la posición del jugador es las misma que la celda que se esta iterando en i entonces se dibuja el personaje
        }
    }

}
void Move(int HeroPos, char GameMap[5])
{
    for(int i = 0; i < 5; i++)
    {
        DrawMap(HeroPos, GameMap);
        cout << endl;
        HeroPos = HeroPos + 1;

    }
}

int main()
{
    int HeroPos = 0;//posición del heroe
    char GameMap[5] = {'1','1','1','1','1'};//Celdas que contienen caracteres(mapa)


    Move(HeroPos, GameMap);//Llamo a la función

    return 0;
}

Código de la clase no me corría era porque using namespace std; lo estaba poniendo muy abajo y compilador no reconocía función cout.

#include <iostream>

using namespace std;

void drawMap(int heroPos, char gameMap[5]){

    for(int i = 0 ; i < 5; i++){

        if(i != heroPos){

            cout << gameMap[i];
        }else{

            cout << 'H';
        }


     }

}


int main()
{
    int heroPos = 1;
    char gameMap[5] = {'1','1','1','1','1'};


    drawMap(heroPos,gameMap);

    return 0;
}

cabe aclarar que las comillas dobles son diferentes de las simples a mi me arrojaba un error devido a esto. comillas simples = alt 39.

*Mis apuntes sobre “Dibujando el mapa de nuestro juego con arreglos”:
Les comparto un pequeño código que modifiqué, donde te permite ingresar la nueva posición que quieres para el héroe y redibuja el mapa con su nueva posición.

#include <iostream>

using namespace std;

void drawMap(int heroPos, char gameMap[5])
{
    for(int i=0;i<5;i++)
    {
        if(i!=heroPos)
        {
        cout<<gameMap[i];
        }else
        {
            cout<<'H';
        }
    }
}

int main()
{
    int heroPos;
    char gameMap[5]={'1','1','1','1','1'};
    drawMap(0,gameMap);
    cout<<endl<<endl<<"This is the map, now decide between 0 and 4 the position of the Hero: ";
    cin>>heroPos;
    cout<<endl<<endl;
    drawMap(heroPos,gameMap);

    return 0;
}

Vamos por buen camino!