Advertisement
Guest User

Snake

a guest
Oct 22nd, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. #include <iostream>
  2. #include <stdlib.h>
  3. #include <conio.h>
  4. #include <windows.h>
  5. using namespace std;
  6. bool gameOver;
  7. const int width=20;
  8. const int height=20;
  9. int x,y,fruitX,fruitY,score;
  10. enum eDirecton{STOP=0,LEFT,RIGHT,UP,DOWN};
  11. eDirecton dir;
  12. void setup()
  13. {
  14. gameOver=false;
  15. dir=STOP;
  16. x=width/2;
  17. y=height/2;
  18. fruitX=rand()%width;
  19. fruitY=rand()%height;
  20. score=0;
  21. }
  22. void draw()
  23. {
  24. system("cls");
  25. for(int i=0;i<width+2;i++)
  26. cout<<"#";
  27. cout<< endl;
  28.  
  29. for(int i=0;i<width;i++)
  30. {
  31.  
  32.  
  33. for(int j=0;j<width;j++)
  34. {
  35. if(j==0)
  36. cout <<"#";
  37. if(i==y&&j==x)
  38. cout <<"O";
  39. else if(i==fruitY&&j==fruitX)
  40. cout <<"F";
  41. else
  42. cout<<" ";
  43. if(j==width-1)
  44. cout <<"#";
  45.  
  46. }
  47. cout <<endl;
  48. }
  49.  
  50.  
  51.  
  52. for(int i=0;i<height+2;i++)
  53. cout <<"#";
  54. cout <<endl;
  55. cout <<"score:"<<score<<endl;
  56.  
  57.  
  58.  
  59. }
  60. void input()
  61. {
  62. if(_kbhit())
  63. {
  64. switch(getch())
  65. {
  66. case 'a':
  67. dir=LEFT;
  68. break;
  69. case 'd':
  70. dir=RIGHT;
  71. break;
  72. case 'w':
  73. dir=UP;
  74. break;
  75. case 's':
  76. dir=DOWN;
  77. break;
  78. case 'x':
  79. gameOver=true;
  80. break;
  81. }
  82. }
  83. }
  84. void logic()
  85. {
  86. switch(dir)
  87. {
  88. case LEFT:
  89. x--;
  90. break;
  91. case RIGHT:
  92. x++;
  93. break;
  94. case UP:
  95. y--;
  96. break;
  97. case DOWN:
  98. y++;
  99. break;
  100. default:
  101. break;
  102.  
  103. }
  104. //if (x>width||x<0||y>height||y<0)
  105. // gameOver=true;
  106. if(x>=width)x=0; else if(x<0)x=width-1;
  107. if(y>=height)y=0; else if(y<0)y=height-1;
  108. if(x==fruitX&&y==fruitY)
  109. {score++;
  110. fruitX=rand()%width;
  111. fruitY=rand()%height;}
  112.  
  113.  
  114. }
  115. int main()
  116. {
  117. setup();
  118. while(!gameOver)
  119. {
  120. draw();
  121.  
  122. input();
  123. logic();
  124. Sleep(100);
  125. }
  126.  
  127. return 0;
  128. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement