Thread: Snake or nib or tron

  1. #1
    Registered User
    Join Date
    Mar 2002
    Posts
    5

    Angry Snake or nib or tron

    This is really starting to bother me...

    How would I move a character across the screen with the arrow keys and continously keep moving in that direction until another character is pressed. I can't figure it out. I would rather not get a link to a page with a snake game code on it.

    thanks..

  2. #2
    Registered User sean345's Avatar
    Join Date
    Mar 2002
    Posts
    346
    Here is some code from Game Tutorials that uses a Windows Console. Obviously this can be used in windows.
    Code:
    BOOL MovePlayer(CHAR_INFO screenBuffer[], COORD *playerPos)						
    {													
    	INPUT_RECORD InputRecord;							// Here is our structure to hold the information on the input buffer (what the user does)
    	COORD oldPosition = *playerPos;						// This stores the old player positive so we can erase it when we move.
    	DWORD Events=0;										// We create DWORD to be compatible with ReadConsoleInput().  (Holds how many input events took place)
    	HANDLE hInput;										// This will be used to query the keyboard
    	BOOL bPlayerMoved = FALSE;							// This holds if the player move or not
    	int bKeyDown = 0;									// This tells us if we pressed DOWN a key, not UP too
    				
    	hInput = GetStdHandle(STD_INPUT_HANDLE);			// Here we initialize our input handle "hInput"  A HANDLE could be many things so we specify
    														// Read in the input from the user, storing the information into the InputRecord structure.
    	ReadConsoleInput(hInput, &InputRecord, 1, &Events);
    													
    	// Now we check if there was a keyboard event.
    
    	// For Windows 95 and 98, we don't need this, but for NT based systems, it handles
    	// the console functions different.  In Windows 95 and 98, it only registers a key
    	// when the key is pressed down, where NT OS's register the key up and key down.
    	// This makes the player go 2 moves every time, so we need to make sure we just
    	// move the player when the key is DOWN.  We use the bKeyDown variable stored in the
    	// input record, then just make sure it equals "true" when a key is hit.
    	// Notice the "&& bKeyDown" in the following if statement.  That says that if the key
    	// was pressed, we only want to enter that if statement if it was a key down press.
    	bKeyDown = InputRecord.Event.KeyEvent.bKeyDown;
    
    	if(InputRecord.EventType == KEY_EVENT && bKeyDown)
    	{													// If the user hit the keyboard:
    														// Check to see if the user hit the RIGHT arrow key														
    		if(InputRecord.Event.KeyEvent.wVirtualKeyCode == VK_RIGHT)
    		{												
    			if(playerPos->X < (SCREEN_WIDTH - 1) )		// Check to make sure our new position doesn't go outside of our buffer
    			{
    				playerPos->X++;							// Increase the player's X value because we are going RIGHT.
    				bPlayerMoved = TRUE;					// Set the flag to TRUE that the player moved
    			}
    		}	
    														// Check to see if we hit the LEFT arrow key
    		else if(InputRecord.Event.KeyEvent.wVirtualKeyCode == VK_LEFT)
    		{										
    			if(playerPos->X > 0)						// Check to make sure our new position doesn't go outside of our buffer
    			{
    				playerPos->X--;							// Increase the player's X value because we are going LEFT.
    				bPlayerMoved = TRUE;					// Set the flag to TRUE that the player moved
    			}
    		}											
    														// Lets check if we hit the UP arrow:								
    		else if(InputRecord.Event.KeyEvent.wVirtualKeyCode == VK_UP)
    		{
    			if(playerPos->Y > 0)						// Check to make sure our new position doesn't go outside of our buffer
    			{
    				playerPos->Y--;							// Increase the player's X value because we are going UP.
    				bPlayerMoved = TRUE;					// Set the flag to TRUE that the player moved
    			}
    		}	
    														// Let's check if we hit the DOWN 
    		else if(InputRecord.Event.KeyEvent.wVirtualKeyCode == VK_DOWN)
    		{							
    			if(playerPos->Y < (SCREEN_HEIGHT - 1) )		// Check to make sure our new position doesn't go outside of our buffer
    			{
    				playerPos->Y++;							// Increase the player's X value because we are going DOWN.
    				bPlayerMoved = TRUE;					// Set the flag to TRUE that the player moved
    			}
    		}												// If we hit ESCAPE
    		else if(InputRecord.Event.KeyEvent.wVirtualKeyCode == VK_ESCAPE)
    		{												
    			exit(0);									// Quit the program
    		}
    	}	
    	
    	FlushConsoleInputBuffer(hInput);					// This clears the input buffer each time so it doesn't echo.
    
    	// If the player moved
    	if(bPlayerMoved)
    	{
    		// Here we check for collision with a wall.  If our new positive is the same X and Y
    		// as a wall, we want to set the characters position back to it's old position.
    		// Otherwise, if it isn't a wall, then we want to erase the old position with a space
    
    		// If we didn't hit a wall, erase the old position
    		if(screenBuffer[playerPos->X + playerPos->Y * SCREEN_WIDTH].Char.AsciiChar != WALL)
    		{
    			// Erase the old position of the player with a space
    			screenBuffer[oldPosition.X + oldPosition.Y * SCREEN_WIDTH].Char.AsciiChar = ' ';
    			screenBuffer[oldPosition.X + oldPosition.Y * SCREEN_WIDTH].Attributes = 0;
    		}
    		else // We hit a wall
    		{
    			// Set the players position back to it's old position (Hence, we collided)
    			*playerPos = oldPosition;
    		}
    
    		return TRUE;									// Return true to say we need to redraw the screen
    	}
    
    	return TRUE;										// We didn't move so return false
    }
    It is pretty well documented, but it basically gets the current key and then determines which arrow was hit or if escape was hit and then follows the appropiate command.

    - Sean
    If cities were built like software is built, the first woodpecker to come along would level civilization.
    Black Frog Studios

  3. #3
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    Basically, you store the last pressed key in a variable.

    Code:
    typedef enum{Left, Right, Up, Down} Direction;
    
    Direction PlayerDirection = Left //Starting direction
    
    while(GameIsOn)
    {
       //Reads the player input
       if( *Player pressed Left key* ) PlayerDirection = Left;
       if( *Player pressed Right key* ) PlayerDirection = Right;
       ...and so on
    
       //Moves the player
       switch(PlayerDirection)
       {
          case Left:
             PlayerXposition--;
          break;
          case Right:
             PlayerXposition++;
          break;
          ...and so on
       }
    }
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  4. #4
    Registered User
    Join Date
    Dec 2001
    Posts
    479
    can u show a small example?
    Last edited by pode; 05-30-2002 at 02:49 PM.

  5. #5
    Registered User
    Join Date
    Dec 2001
    Posts
    479
    what does enum mean and is that all u need to do?

  6. #6
    Registered User Dual-Catfish's Avatar
    Join Date
    Sep 2001
    Posts
    802
    Ugh, I really think the answer to this question should be stickied... it's been asked and answered about 100 times.

    It's something like

    while (!kbhit)
    {
    do_stuff();
    }
    char ch = getch();
    do_move();

  7. #7
    Registered User
    Join Date
    Dec 2001
    Posts
    479
    what, the enum?

    why dont u post something that works.
    yes i am asking for allready made code
    cause i've had this problem for about 6 mounths!

  8. #8
    Registered User
    Join Date
    Aug 2001
    Posts
    380
    I copied the delay() off of one of these forums.

    Code:
    #include <stdio.h>
    #include <time.h>
    #include <conio.h>
    void delay ( long m );
    main()
    {
    	int x = 5,y = 5;
    	int oldx,oldy;
    	char move  = 'd';
    	int quit = 0;
    	while(!quit)
    	{
    		oldx = x;
    		oldy = y;
    	  while(kbhit())
    	  {
    		 move = getch();
    	  }
    	  switch(move)
    	  {case 'a' : x--;break;
    		case 'd' : x++;break;
    		case 's' : y++;break;
    		case 'w' : y--;break;
    		case 'q' : quit = 1;
    	  }
    	  if(x < 1 || x > 80)
    		x = oldx;
    	  if(y < 1 || y > 24)
    		y = oldy;
    	  gotoxy(x,y);
    	  printf("*\b");
    	  delay(1);
    	}
    }
    
    
    
    void delay ( long m )
    {
      clock_t limit, cl = clock ();
      limit = cl + m;
      while ( limit > cl )
    	 cl = clock ();
    }

  9. #9
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    You use enum if you want to define a set of constants with values that isn't important (like directions, you could as well define UP as the number -4086).

    Instead of typing:

    const int Left 0;
    const int Right 1;
    const int Up 2;
    const int Down 3;

    You type:

    enum{Left, Right, Up, Down};

    Makes it simplier, huh?
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  10. #10
    Rambling Man
    Join Date
    Jan 2002
    Posts
    1,050
    Makes it simplier, huh?
    That's very nice to know indeed.

  11. #11
    Registered User
    Join Date
    Mar 2002
    Posts
    5
    Dual-Catfish,

    What exactly does your code do and what libraries do i need to include?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A snake game - Memory problem
    By gavra in forum C Programming
    Replies: 29
    Last Post: 11-23-2008, 12:58 PM
  2. Need help with a snake game (ncurses)
    By Adam4444 in forum C Programming
    Replies: 11
    Last Post: 01-17-2007, 03:41 PM
  3. Contest - Snake Numbers
    By pianorain in forum Contests Board
    Replies: 46
    Last Post: 06-15-2006, 07:52 AM
  4. Snake
    By Grantyt3 in forum Game Programming
    Replies: 2
    Last Post: 05-24-2006, 01:35 PM
  5. linked list problem
    By kzar in forum C Programming
    Replies: 8
    Last Post: 02-05-2005, 04:16 PM