Snake game help

Started by
5 comments, last by Kotorez 10 years, 11 months ago
Hello, I am trying to do a snake game and I am stuck on the step where I have to make a game loop. I want my snake to move automatically until it hits the wall or user steers it into a different direction. I tried to make a function "playerAutomove" that records the user's last move so the game loop knows where the snake turned (up,down,left,right) but it seems like no matter what I do the program will stop and wait for user's key press, similar to "cin". I just need a suggestion, you dont have to give me the exact code. :) This is what I have so far. The code should compile under c++11 if you just copy/paste. I used only default libraries that c++ comes with. http://pastebin.com/g05vYALt Thanks
Advertisement

You would want to make your loop look something like this:


bool run = true;

int main()
{
   // init stuff
   Init();
   
   while(run)
   {
      HandleInput();
      UpdateGameLogic();
      Render();
   {
}

Right now, everything before the while loop is only called once and while run remains true, you will keep looping and call these 3 functions that should handle how your game is working.

Here is my problem in a small code. It appears that getch() stops it from looping. In this small example I want "Hello world" to be printed infinite amout of times and not care about if user entered something or not.


#include <stdio.h>
#include <conio.h>
#include <iostream>

using namespace std;

int main ()
{
    bool run = true;
    int ch;

    while (run){
        printf("hello world");
        ch = getch();  

            if (ch == 0 || ch == 224)
                cout << getch();
            printf("\n");
            if (ch == 27)
                run = false;
    }
    printf("ESC %d\n", ch);

    return 0;
}
 

Do I have to create a separate thread for input handling or there is a simpler solution for this?

getch() will lock the calling thread which is something you mostly want to do in console applications as you are probably expecting user input before you want to continue doing something based on that input. In games that run in real-time, you don't want to have your main thread locked because, like you experience now, will stop at that point and not continue.

Creating a separate thread in this case could potentially solve it, but it's a bit overkill in this case. Instead, you want to keep your main thread going. This link explains how _getch() works and provides _getch_nolock() as a non-thread locking solution.

This will probably work fine for a console app, but once you go further, you will not be able (or shouldn't at least) to use those functions. For simplicity and testing purposes, I generally make use of GetASyncKeyState().

Try searching the forum or use google for some more elegant solutions, I'm sure you will be able to find some useful information. :)

Use the console-specific functions in wincon.h (which is included in windows.h) rather than conio and the system functions. Edit: conio is not standard C++ anyway and you should not use system() (read here). You can find documentation on the functions specific to the Windows console here, and a bit more general information about the console provided by Microsoft here.

To answer your question in that light, check the console's input buffer to see if there are any input events using GetNumberOfConsoleInputEvents. If there are, use ReadConsoleInput to grab them and handle them appropriately (you will need to obtain the necessary information from the event structure first), then move on to the rest of your loop. If there are no events in the buffer when you check, then you just move on to updating the snake's position. You should use the functions specific to the Windows console to control the output as well. For example, do not clear the console screen with system("cls"). Write your own function to clear the screen making use of FillConsoleOutputCharacter (which will unfortunately require you to obtain some other info about the console as well). There's a nice breakdown of the ways (good and bad) to clear the console window here.

And I know it seems like I just upped the complexity of Snake by a factor of a hundred. biggrin.png If you're going to spend any amount of time with the Windows console for anything other than plain text games, spending an afternoon learning how to work with it properly is worthwhile IMO. Ultimately it will feel very simple, I promise.

Anyway, to keep the snake moving when there is no user input, you should keep track of the direction the head is moving in addition to its location. User input should change this direction when appropriate. When you update the location of the snake, it's new location is based on its current location and the direction. You might have other things change the direction of the snake as well, such as a collision with the wall of your "garden".

If you want to stick with conio, you may be able to use kbhit(), which will return 0 if no keyboard key has been hit. Thus in your HandleInput() funciton you would 1st check:

if (kbhit()) {
  input = getch();
  ...
}

My Gamedev Journal: 2D Game Making, the Easy Way

---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)

Wow great help guys! That should keep me busy for a while :)

This topic is closed to new replies.

Advertisement