2009-05-03 1 views
0

Я создал этот код, и когда я запустил его, не получайте никаких ошибок до тех пор, пока стрелка не покинет экран (то есть: (* I) -> x> maxx), после чего O будет беспорядочно телепортироваться (ну, Я предполагаю, что это не случайно, но я пытаюсь найти шаблон для него).Почему значение x изменяется в этой программе?

РЕДАКТИРОВКА: случайная телепортация, похоже, не возникает, если я двигаюсь вверх, и, если я опустился вниз, О телепортируется прямо на дно. Кроме того, произошел сбой, когда O становится «>». (Я пытаюсь выяснить, как это происходит)

РЕДАКТИРОВАТЬ: сбой в «-» - «>» происходит, если O находится в правом нижнем углу экрана (player.x = 9; player.y = 9) и вводится последовательность «wqs».

EDIT: Я удалил объявления классов, потому что я уверен, что ошибка находится в пределах _move() s и check().

EDIT: Преобразование глюк появляется происходит, когда «WQ» набирается, то любой другой символ вводится (т.е. «skiping» следующий шаг)

EDIT: tranform глюк происходит при player.x = 9 ; player.y = 8; а затем 'д' нажата, следующий ход игрок tranforms в '>'

Это код:

#include<vector> 
#include<iostream> 
#include<string> 
using namespace std; 
const int maxx = 10, maxy = 10; //two constants that show the size of the sector 
char sector[maxx][maxy]; //array of characters used to display the sector 
prgm player(0, 0, 'O'); //player definition at x0,y0,and displayed with 'O' 
const int vsize = 1; //size of the enemy array (ie: how many enemies there will be 
X1 a(9, 5, 'X', 10); //enemy "a", has a move function that moves it back and forth 
virus * viral_data[vsize] = {&a}; //array of enemies used to set the sector 
vector<antivirus*> antiviral_data; //vector of pointers to "antivirus" the weapon used 
vector<antivirus*>::iterator I; //iterator for previous vector 

void display() //function to display the sector 
{ 
    for(int i = 0; i < maxy; i++) 
    { 
     for(int j = 0; j < maxx; j++) 
     { 
      cout<<sector[j][i]; 
     } 
     cout<<endl; 
    } 
    return; 
} 

void p_move() //function to get players input, then move the player or create "antivirus" 
{ 
    char dir; 
    cin>>dir; 
    switch(dir) 
    { 
    case 'w': 
     player.y--; 
     break; 
    case 'a': 
     player.x--; 
     break; 
    case 's': 
     player.y++; 
     break; 
    case 'd': 
     player.x++; 
     break; 
    case 'q': 
     antiviral_data.push_back(new aX1(player.x, player.y, '>')); //creates a new aX1 at the players position 
     break; 
    } 
    return; 
} 

void v_move() //uses the enemies move 
{ 
    for(int i = 0; i < vsize; i++) 
    { 
     viral_data[i]->move(); 
    } 
    return; 
} 

void a_move() //uses the weapon (ie: moves the weapon forward) 
{ 
    for(I = antiviral_data.begin(); I < antiviral_data.end(); I++) 
    { 
     (*I)->move(); 
    } 
    return; 
} 

void set() //sets the sector array (char) 
{ 
    for(int i = 0; i < maxy; i++) 
    { 
     for(int j = 0; j < maxx; j++) 
     { 
      sector[j][i] = ' '; makes the entire sector blank 
     } 
    } 
    sector[player.x][player.y]=player.sym; //sets the sector at the player's position to 'O' 
    for(int i = 0; i < vsize; i++) 
    { 
     sector[viral_data[i]->x][viral_data[i]->y] = viral_data[i]->sym; //sets the sector at each enemy's position to be 'X' 
    } 
    for(I = antiviral_data.begin(); I < antiviral_data.end(); I++) 
    { 
     sector[(*I)->x][(*I)->y] = (*I)->sym; //sets the sector at each weapon's position to be '>' 
    } 
    return; 
} 

void check() //prevents the player from moving off the screen, erases bullet if it moves of the screen (to prevent access to non-allocated memory) 
{ 
    if(player.x < 0) 
    { 
     player.x = 0; 
    } 
    if(player.y < 0) 
    { 
     player.y = 0; 
    } 
    if(player.x > (maxx-1)) 
    { 
     player.x = (maxx-1); 
    } 
    if(player.y > (maxy-1)) 
    { 
     player.y = (maxy-1); 
    } 
    //PROBLEM APPEARS TO OCCUR HERE 
    for(I = antiviral_data.begin(); I! = antiviral_data.end();) 
    { 
     if((*I)->x > maxx) 
     { 
      I = antiviral_data.erase(I); 
     } 
     else 
     { 
      I++; 
     } 
    } 
    //*-*-*-*-*-*-*-*-*-*-*-*-*-*-* 

    return; 
} 
int main() 
{ 
    while(true) 
    { 
     set(); //set sector 
     display(); //display sector 
     p_move(); //player's move 
     v_move(); //enemy's move 
     a_move(); //bullet's move 
     check();//check moves 
    } 
    return 0; 
} 
+0

Ваше отсутствие пробелов между токенами делает ваш код тяжело трудным для чтения. – tpdi

+1

попытайтесь изолировать проблему до определенной части вашей программы, а затем опубликуйте этот фрагмент кода. Также почему это сообщество wiki? – Naveen

+1

И ваше использование глобалов означает все виды прокрутки вверх и вниз для определения типов переменных. Это не похоже на то, что вы платите компилятору за разобранный персонаж. – tpdi

ответ

6

В чеке(), тест

((*I)->x > maxx) 

должны be

((*I)->x >= maxx) 

. Это ошибка за один раз, которая позволяет> получить один квадрат от экрана. Когда процедура отображения пытается отобразить ее, она сжимает символ дисплея для X.

+1

Вы любезная душа, чтобы пахать его код и помочь ему. – DOK