random generator food in a simple game

I am writing a simple snake game, but there is a bug in the random food generator. The food will don't know somehow, disappear like that even thought i had set the random position within the range. i wrote a test function to test it separately, but still can't figure out where is the bug. Please help me, Thank you very much >.<

Here is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
 #include <iostream>
#include <ncurses.h>

using namespace std;

const int width = 20;
const int height = 20;
int x, y, foodx, foody;
int preXfood, preYfood;
int score = 0;


void draw();

int kbhit();

void foodposition();

void check();

int main()
{
  foodposition();

  draw();

  char next;

  foodx = rand()%(width-2);
  foody = rand()%(height-1); 

  
  do
  {     
      foodposition();
      draw();
      system("stty raw");
      cin >> next;
      system("stty cooked");
      score = score +10;
  }while(next!='k');


}

void draw()
{
  system("clear");

  for(int i = 0; i < width; i++)
    cout << "#";
  cout << endl;

  for(int j = 0; j < height; j++)
  {
    for(int i = 0; i <width; i++)
    {
      if(i ==0)
        cout << "#";
      else if(i == width -1)
        cout << "#";
      else if(i == x && j == y)
        cout << "O";
      else if(i == foodx && j == foody)
        cout << "F";
      else
          cout << " ";
     }
    cout << endl;
  }

  for(int i = 0; i < width; i++)
    cout << "#";
  cout << endl;

  cout << "Score :" << score <<endl ;

  
  }

int kbhit()
{
    system("stty raw");
    char ch = getch();
    if (ch != ERR) {
        ungetch(ch);
        return 1;
    } else {
        return 2;
    }
    system("stty cooked");
}

void foodposition()
{
  preXfood = foodx;
  preYfood = foody;

  foodx = rand()%(width-2);
  foody = rand()%(height-1);  

  if(preXfood == foodx && preYfood == foody)
    foodposition();
  else if( x == foodx && y == foody)
    foodposition();
}

void check()
{
    char next;

    cin >> next;

    if(next == ' ')
    {
      foodposition();
    }
}


It seems to happen when foodx == 0.
i don't think so, i had added one more line

1
2
else if(foodx == 0 && foody == 0)
        foodposition();
OKOK, i got it, problem solved :) tq

i should write like this

1
2
else if(foodx == 0 || foody == 0)
        foodposition();
Topic archived. No new replies allowed.