2014-02-03 5 views
0

Вчера я занимался домашней работой, я сделал большую часть этого, но не мог сделать главное. Я не знаю, почему это не работает. Я спросил других студентов, но никто не знает, в чем проблема. В основном эта программа - небольшая игра, в каждой команде - 18 игроков. программа случайным образом дает игрокам координаты и направления, и они начинают двигаться. Я в основном сделал программу, но у меня проблемы с полем, она вообще не показывает игроков. Я пробовал много вещей, и при тестировании заметил, что он не печатает даже тестовую строку в выражении if, которое я написал. когда я пишу это поле части [i] [j] = & игроков [k] [0]; Я проверил, действительно ли поле [i] [j] получает координату x и y, и да, да. но в классе print_field значение поля [] [] равно null, и поле пусто. игроки - это массив структур. field - массив указателей, указывающих на игроков или NULL.Печать 2 мерных массива указателей на структуры

Я пробовал все свои знания и не мог сделать лучше. Что не так с этим кодом? Почему он не показывает игроков на поле?

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <time.h> 
#define LENGTH 25 
#define WIDTH 25 
enum direction {Right, Left, Up, Down};    /*Right = 0, Left = 1, Up = 2, Down = 3*/ 

void print_field(); 
void random_positions(); 
void playerdirection(); 
void motion(); 
void game(); 

struct player 
{ 
char *dora;  
char *team; 
char *name;  //string? 
int x,y;   //coordinates  
int direction;  
}; 
typedef struct player Player; 
struct player *field[WIDTH][LENGTH]; 
Player players[8][1]; 
int main() 
{ 
    srand (time(NULL)); 
    int i;    //players 9 in each team team1 = 0 team2 = 1 
    players[0][0].name = "A1"; 
    players[1][0].name = "A2"; 
    players[2][0].name = "A3"; 
    players[3][0].name = "A4"; 
    players[4][0].name = "A5"; 
    players[5][0].name = "A6"; 
    players[6][0].name = "A7"; 
    players[7][0].name = "A8"; 
    players[8][0].name = "A9"; 
    players[0][1].name = "B1"; 
    players[1][1].name = "B2"; 
    players[2][1].name = "B3"; 
    players[3][1].name = "B4"; 
    players[4][1].name = "B5"; 
    players[5][1].name = "B6"; 
    players[6][1].name = "B7"; 
    players[7][1].name = "B8"; 
    players[8][1].name = "B9"; 
    for(i = 0; i < 9 ; i++) 
    { 
      players[i][0].team = "Team A"; 
      players[i][1].team = "Team B"; 
      players[i][0].dora = "Alive"; 
      players[i][1].dora = "Alive";  
    } 
    random_positions(); 
    playerdirection(); 
    print_field(); 
    motion (Player player); 
    print_field(); 
    game();  
    return 0; 
} 

void random_positions() 
{ 
    int i,j,k; 
    int xs[17],ys[17]; 
    for(i= 0; i<9 ; i++) 
    { 
     players[i][0].x = rand() % 25; 
     players[i][0].y = rand() % 25; 
     players[i][1].x = rand() % 25; 
     players[i][1].y = rand() % 25; 
     printf("A%d x = %d y = %d \n",i+1,players[i][0].x,players[i][0].y); 
     printf("B%d x = %d y = %d \n",i+1,players[i][1].x,players[i][1].y);   
    } 
    for(i = 0; i < 9 ; i++) 
    { 
      xs[i] = players[i][0].x; 
      xs[i+8] = players[i][1].x; 
      ys[i] = players[i][0].y; 
      ys[i+8] = players[i][1].y; 
      for(j = 0; j <= i ; j++) 
      { 
       //printf("j%d start\n",j); 
       if(i != j && xs[i] == xs[j]) 
       { 
         //printf("i%d start\n",j); 
         if(ys[i] == ys[j]) 
         { 
           return random_positions();          
         } 
         //("j%d done\n",j); 
       } 
       //printf("j%d done\n",j); 
      } 
    } 
    for(i = 0; i < 25; i++) 
     { 
       for(j = 0; j < 25; j++) 
       { 
        for(k = 0; k < 9; k++) 
        { 
          if(i == players[k][0].x && j == players[k][0].y) 
          { 
           field[i][j] = &players[k][0]; 
          } 
          if(i == players[k][1].x && j == players[k][1].y) 
          { 
           field[i][j] = &players[k][1]; 
          } 
          else field[i][j] = NULL;        //I da J sheidzleba shesacvleli iyos 
        }   
       }  
     }  
}  

/*this function prints out the given state of the field*/ 
void print_field(){ 
int i,j; 
printf("\n"); 
printf("|0 1 2 3 4 5 6 7 8 9 101112131415161718192021222324|\n"); /*just to show easier the allignment*/ 
for(j=0; j<WIDTH+2; j++)  /*This first loop goes through row and creates them each by each*/ 
{ 
     if(j == 0 || j == WIDTH +1)   /*creates the upper and lower part of the field*/ 
       for(i=0; i<LENGTH+2; i++)  /*there should be space for frame so I added 2 to LENGTH in the loop*/ 
       {   
        if(i==0) 
        printf("-"); 
        else if(i == LENGTH+1) 
        printf("-\n"); 
        else printf("--");  /*3 decimals*/ 
       } 
     else 
       for(i=0; i<LENGTH+2; i++)  /*Goes through the columns in this row and creates either frame or puts the nodeid*/ 
       { 
        if(i==0)printf("|");  /*frame*/ 
        else if(i == LENGTH+1) printf("| %d\n",(j-1)); /*frame*/ 
        else if(field[j-1][i-1] != NULL) 
        { 
         printf("aaa"); 
         printf("%-*s",2,(*field[j-1][i-1]).name);  /*putting nodeid 3 decimals*/ 
        } 
        else printf(" "); 
       }   
} 
printf("\n"); 
} 
+0

Здесь 'void motion (Player player);' и здесь 'void game();' вам нужно будет удалите 'void'. Вы не вызываете функцию с ее возвращаемым типом. Просто 'motion (Player player);' и 'game()'. И у вас есть прототипы функций над вашим 'main()'? – pzaenger

+0

О да, это правильно, thx для предупреждения плохо правильно, что :) – Vato

+0

Что такое 'игроки'? – m0skit0

ответ

1

Вам нужно Player[9][2] вместо Player[8][1]. Вы должны инициализировать массив своей длиной, хотя вы можете получить доступ только к индексу до length - 1, потому что массивы индексируются с 0.

Смежные вопросы