2010-11-05 43 views
2

下面的代碼段錯誤的問題(這也是貼at pastebin):簡單的遊戲在C中使用getch - segfault問題?

#include <stdio.h> 
#include <string.h> 
#include <stdbool.h> 
#include "mygetch.h" 

#define MAX_SIZE 255 
#define SCR_CLEAR "\033[2J\033[;H" 

void getgrid(int, int); 
void resetgrid(void); 
void getkey(void); 


static bool grid[5][5] = {{0,0,0,0,0}, 
          {0,0,0,0,0}, 
          {0,0,0,0,0}, 
          {0,0,0,0,0}, 
          {0,0,0,0,0}}; 


int main() { 

    while(1) { 
     getkey(); 
    } 


    return 0; 
} 

void getgrid(int xpos, int ypos) { 
    int x = 0; 
    int y = 0; 

    grid[xpos][ypos] = 1; 

    for(x = 0; x <= 4; x++) { 
     for(y = 0; y <= 4; y++) { 
      printf("%i ", grid[x][y]); 
     } 
     printf("\n"); 
    } 
} 


void resetgrid() { 
    int x = 0; 
    int y = 0; 

    for(x = 0; x <= 4; x++) { 
     for(y = 0; y <= 4; y++) { 
      grid[x][y] = 0; 
     } 
    } 
} 

void getkey() { 
    static int xpos = 0; 
    static int ypos = 0; 
    int c = mygetch(); 

    //0x41 = up.. apparently on my linux console? 
    //0x42 = down 
    //0x44 = left 
    //0x43 = right 

    if(c == 0x41 && ypos != 0) { 
     ypos--; 
    } else if(c == 0x42 && ypos != 4) { 
     ypos++; 
    } else if(c == 0x44 && xpos != 4) { 
     xpos--; 
    } else if(c == 0x43 && xpos != 0) { 
     xpos++; 
    } 

    resetgrid(); 
    printf(SCR_CLEAR); 
    getgrid(xpos, ypos); 
} 

你可以假設mygetch()返回一個ASCII整數代碼點,我的Linux控制檯了下來左和右是A/B/C/D,所以我將它們映射爲如此。

我的問題是由於某些原因,即使我正確地定義了多維數組,當我按下向上/向下/向左/向右和向右不工作時,他們離開屏幕並導致段錯誤,現在我知道鍵正確映射,所以我不知道爲什麼y--y++等將不會正常工作,除非我在定義數組或其他地方出錯。

我肯定會從修復這個問題和做更多的東西中學到很多東西,但這只是我想要做的一件有趣的事情。

+0

我感動引擎收錄的內容進入後。恕我直言,最好是在可能的情況下將問題保持在自給自足的狀態,以便即使在外部網站得到更新時仍保持相關。 – RBerteig 2010-11-05 08:06:31

回答

3

您的邊界條件反轉爲左側右側。你應該有:

if (c == 0x41 && ypos != 0) { 
    ypos--; 
} else if(c == 0x42 && ypos != 4) { 
    ypos++; 
} else if(c == 0x44 && xpos != 0) { 
    xpos--; 
} else if(c == 0x43 && xpos != 4) { 
    xpos++; 
} 

相反的:

if (c == 0x41 && ypos != 0) { 
    ypos--; 
} else if(c == 0x42 && ypos != 4) { 
    ypos++; 
} else if(c == 0x44 && xpos != 4) { 
    xpos--; 
} else if(c == 0x43 && xpos != 0) { 
    xpos++; 
} 
+0

謝謝,它完美的作品。由於某些奇怪的原因,這些軸是顛倒的,但修復起來要簡單得多,我現在正在進入遊戲的「有趣」部分! – John 2010-11-05 06:33:56