Error assigning value to struct property in C++

Asked

Viewed 129 times

1

I’m learning to code and, at the moment, trying to make a little game like the popular Nake. We need to increase several things in the program, such as the limits of the walls, collisions, etc... Then the following code is a sketch of the game just to check if the Nake can move on the screen and increase in size while eating the fruit. The code:

#include<cstdio>
#include<vector>
#include<conio.h>
#include<stdlib.h>
#define LIN 20
#define COL 80
using namespace std;
int tela[LIN][COL];
void printtela(){
    int i, j;
    for(i=0;i<LIN;i++){
    for(j=0;j<COL;j++){
        switch(tela[i][j]){
            case 0:
                printf(" ");
                break;
            case 1:
                printf("O");
                break;
            case 2:
                printf("X");
                break;
            }
        }
    printf("\n");
    }
}
vector<int> cobra; 
struct coord {
    int x;
    int y;
};
coord pedaco[800];
pedaco[0].x=1;
pedaco[0].y=1;
cobra.push_back(pedaco[0]);
int main (){
     char com;
     int headx=0, heady=0, fruitx, fruity, i, j;
     bool endgame=0;
     fruitx=rand()%19;
     fruity=rand()%79;
     tela[fruitx][fruity]=2;
     while (!endgame){
         com = getch();
         printf("\e[H\e[2J"); //limpa tela
         switch(com){
        case 'w':
            heady--;
            break;
        case 'a':
            headx--;
            break;
        case 's':
            heady++;
            break;
        case 'd':
            headx++;
            break;
        }
    if (cobra.size()>1){
        for(i=cobra.size();i>0;i--){
            pedaco[i].x=pedaco[i-1].x;
            pedaco[i].y=pedaco[i-1].y;
        }
        pedaco[0].x=headx;
        pedaco[0].y=heady;
    }
    else {
        pedaco[0].x=headx;
        pedaco[0].y=heady;
    }
    for(i=0;i<cobra.size();i++){
        tela[pedaco[i].x][pedaco[i].y]=1;
    }
    printtela();
    }
 return 0;     
}

When compiling, error appears on lines 34, 35, 36

coord pedaco[800];
pedaco[0]. x=1;
pedaco[0]. y=1;

error'pedaco 'does not name a type
error 'cobra' does not name a type
What can I do to fix this? Thanks in advance for the support and attention.

1 answer

0

From what I imagine, you can’t assign any value to variables outside a function context.

I believe passing the code block...

coord pedaco[800];
pedaco[0].x=1;
pedaco[0].y=1;
cobra.push_back(pedaco[0]);

...inside its function main solve your problem

Browser other questions tagged

You are not signed in. Login or sign up in order to post.