Thread: Snake Code Help

  1. #1
    Registered User
    Join Date
    Apr 2013
    Posts
    3

    Snake Code Help

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include "SDL/SDL.h"
    
    
    
    
    
    
    // 16 x 16 pixels for stuff on the screen
    #define px 16
    #define maxrow    30
    #define maxcol    40
    #define snake_start_row    15
    #define snake_start_col    20
    
    
    
    
    
    
    SDL_Surface *screen = NULL;
    
    
    
    
    void make_move();
    
    
    void setup_board();
    
    
    void randomize();
    
    
    
    
    //Global
    int score, snake_length, speed, level,r,c;
    int obstacles=10;
    char grid[maxrow][maxcol];
    int direction = SDLK_RIGHT;
    struct snake_segment {
        int row,col;
    } snake[100];
    
    
    // Start up SDL
    void init() {
        // Start SDL
        SDL_Init(SDL_INIT_EVERYTHING);
        // Set the caption
        SDL_WM_SetCaption("Snake", NULL);
        //Set up Screen
        screen = SDL_SetVideoMode(640,480,32, SDL_SWSURFACE);
    }
    
    
    void draw() {
        // Declare Images
        SDL_Surface *food= SDL_LoadBMP("food.bmp");
        SDL_Surface *obstacle= SDL_LoadBMP("obstacle.bmp");
        SDL_Surface *background= SDL_LoadBMP("background.bmp");
        SDL_Surface *segment= SDL_LoadBMP("segment.bmp");
        SDL_Surface *blank= SDL_LoadBMP("blank.bmp");
        SDL_BlitSurface(background, NULL, screen, NULL);
        
    
    
        
        int row,col,i,j;
        
    
    
    // Plot Obstacle and Food
        SDL_Rect location;
        
        for(row=0;row < maxrow;row++){
            for(col=0;col < maxcol;col++){
                location.y = row * px;
                location.x = col * px;
                if(grid[row][col] == 'o') {
                    SDL_BlitSurface(obstacle, NULL, screen,&location);
                }
                else if (grid[row][col] == 'f') {
                    SDL_BlitSurface(food, NULL, screen, &location);
                }
            }
        }
    
    
        for(i=0;i<snake_length;i++){
                location.y=snake[i].row * px;
                location.x=snake[i].col * px;
                SDL_BlitSurface(segment,NULL,screen,&location);
                
        }    
    }
    
    
    void init_board() {
        int row, col, i,j;
        snake_length=5;
        //Set up Grid
        for(row=0; row<=maxrow;row++){
            for(col=0;col<=maxcol;col++){
                grid[row][col]= ' ';
            }
        }
        // Set up obstacles
        for(i=0;i<=obstacles*2;i++){
            row= rand()%maxrow;
            col= rand()%maxcol;
            if(i<obstacles){
                grid[row][col] = 'o';
            } else {
                grid[row][col] = 'f';        
            }
        }
        
        for(j=0;j<snake_length;j++){
            snake[j].row=snake_start_row;
            snake[j].col=(snake_start_col + j);
        }        
    }
    
    
    int main(int argc, char **argv)
    {
        SDL_Event keyevent;
        init(); // Start SDL
        // initialize the grid
        init_board();
        do { // repeatedly 
            // draw the state of the game
            draw();
            
            // await user input
            make_move();
            
            
            SDL_Flip(screen);
            
            
        } while(1);
        
    
    
    }
    
    
    void make_move(){
        SDL_Surface *blank= SDL_LoadBMP("blank.bmp");
        SDL_Surface *segment= SDL_LoadBMP("segment.bmp");
        SDL_Rect location;
        SDL_Event keyevent;
        int j;
    
    
        if(SDL_PollEvent(&keyevent)){
            if(keyevent.type==SDL_KEYDOWN){// (keyevent.type){
                switch(keyevent.key.keysym.sym){
                    case SDLK_LEFT:
                        snake[snake_length].row=snake[snake_length-1].row; // End segment loses segments go up one row
                        snake[snake_length].col=snake[snake_length-1].col-1;
                        
                        
                        break;
                    case SDLK_RIGHT:
                        snake[snake_length].row=snake[snake_length-1].row; // End segment loses segments go up one row
                        snake[snake_length].col=snake[snake_length-1].col+1;
        
                        
                        break;    
                    case SDLK_UP:
                        snake[snake_length].row=snake[snake_length-1].row-1; // End segment loses segments go up one row
                        snake[snake_length].col=snake[snake_length-1].col;
                        break;
                    case SDLK_DOWN:
                        snake[snake_length].row=snake[snake_length-1].row+1; 
                        snake[snake_length].col=snake[snake_length-1].col;
                        break;
                    case SDLK_x:
                        exit(0);
                }
            
                
            } else if (keyevent.type == SDL_QUIT) {
                exit(0);
            }
            
        }
    
    
            
            SDL_Flip(screen);
    }
    When i compile this code I get my snake situated in the middle of the screen, but it will not move around. I have thought about trying to take the last segment and move it to the [snake_length] to make it move but am stuck.

    Please help if possible,

    Thank you

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    > for(row=0; row<=maxrow;row++)
    > for(col=0;col<=maxcol;col++)
    These overrun your array - remember, it's <, not <=

    > snake[snake_length].row=snake[snake_length-1].row; // End segment loses segments go up one row
    > snake[snake_length].col=snake[snake_length-1].col-1;
    You also need to delete snake[0], and perhaps move snake[1]...snake[snake_length] back one space so it's snake[0]...snake[snake_length-1]
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    You're also calling SDL_Flip twice (once in main and once at the end of make_move); I'm not sure what effect this will have. SDL_Flip is meant for when you have a hardware surface (SDL_HWSURFACE), but you have a software surface so you may need to use SDL_UpdateRect() instead. Try this if you're having trouble getting images painted to the screen.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  4. #4
    Registered User
    Join Date
    Apr 2013
    Posts
    3
    Code:
    SDL_Surface *screen = NULL;
    
    
    void make_move();
    void collision();
    void setup_board();
    void randomize();
    
    
    //Global
    int score,snake_length, speed, level,r,c;
    int obstacles=10;
    char grid[maxrow][maxcol];
    int direction = SDLK_RIGHT;
    struct snake_segment {
    	int row,col;
    } snake[100];
    
    // Start up SDL
    void init() {
    	// Start SDL
    	SDL_Init(SDL_INIT_EVERYTHING);
        // Set the caption
        SDL_WM_SetCaption("Snake", NULL);
    	//Set up Screen
    	screen = SDL_SetVideoMode(640,480,32, SDL_SWSURFACE);
    }
    
    void draw() {
    	// Declare Images
    	SDL_Surface *food= SDL_LoadBMP("food.bmp");
    	SDL_Surface *obstacle= SDL_LoadBMP("obstacle.bmp");
    	SDL_Surface *background= SDL_LoadBMP("background.bmp");
    	SDL_Surface *segment= SDL_LoadBMP("segment.bmp");
    	SDL_Surface *cats= SDL_LoadBMP("cats.bmp");
    	SDL_Surface *blank= SDL_LoadBMP("blank.bmp");
    	SDL_BlitSurface(background, NULL, screen, NULL);
    	
    
    	
    	int row,col,i,j;
    	
    
    // Plot Obstacle and Food
    	SDL_Rect location;
    	
    	for(row=1;row <= maxrow;row++){
    		for(col=1;col <= maxcol;col++){
    			location.y = row * px;
    			location.x = col * px;
    			if(grid[row][col] == 'o') {
    				SDL_BlitSurface(obstacle, NULL, screen,&location);
    			}
    			else if (grid[row][col] == 'f') {
    				SDL_BlitSurface(food, NULL, screen, &location);
    			}
    		
    			
    		}
    	}
    	
    	for(i=0;i<snake_length;i++){
    			location.y=snake[i].row * px;
    			location.x=snake[i].col * px;
    			SDL_BlitSurface(segment,NULL,screen,&location);			
    	}
    
    		SDL_Flip(screen);
    }
    
    void init_board() {
    	int row, col, i,j;
    	snake_length=5;
    	//Set up Grid
    	for(row=0; row<=maxrow;row++){
    		for(col=0;col<=maxcol;col++){
    			grid[row][col]= ' ';
    		}
    	}
    	// Set up obstacles
    	for(j=0;j<=obstacles*2;j++){
    		row= rand()%maxrow;
    		col= rand()%maxcol;
    		if(j<obstacles){
    			grid[row][col] = 'o';
    		} else {
    			grid[row][col] = 'f';		
    		}
    	}
    		
    			
    		
    	
    	
    	for(i=0;i<snake_length;i++){
    		snake[i].row=snake_start_row;
    		snake[i].col=(snake_start_col + i);
    	}		
    }
    
    int main(int argc, char **argv)
    {
    
    	int j,row,col;
    	SDL_Event keyevent;
    	init(); // Start SDL
    	// initialize the grid
    	init_board();
    	
    	do { // repeatedly 
    		
    		// draw the state of the game
    		draw();
    		// await user input
    		make_move();
    		collision();
    	} while(1);
    	
    
    }
    
    void make_move(){
    	SDL_Surface *blank= SDL_LoadBMP("blank.bmp");
    	SDL_Surface *segment= SDL_LoadBMP("segment.bmp");
    	SDL_Rect location;
    	SDL_Event keyevent;
    	int j;
    	
    	
    
    	if(SDL_PollEvent(&keyevent)){
    		if(keyevent.type==SDL_KEYDOWN){// (keyevent.type){
    		
    			switch(keyevent.key.keysym.sym){
    				case SDLK_LEFT:
    					snake[snake_length].row=snake[snake_length-1].row; // End segment loses segments go up one row
    					snake[snake_length].col=snake[snake_length-1].col-1;
    					
    					
    					break;
    				case SDLK_RIGHT:
    					snake[snake_length].row=snake[snake_length-1].row; // End segment loses segments go up one row
    					snake[snake_length].col=snake[snake_length-1].col+1;
    	
    					
    					break;	
    				case SDLK_UP:
    					snake[snake_length].row=snake[snake_length-1].row-1; // End segment loses segments go up one row
    					snake[snake_length].col=snake[snake_length-1].col;
    					break;
    				case SDLK_DOWN:
    					snake[snake_length].row=snake[snake_length-1].row+1; 
    					snake[snake_length].col=snake[snake_length-1].col;
    					break;
    				case SDLK_q:
    					exit(0);
    			}
    				int k;
    			for(k=1;k<=snake_length;k++){
    				snake[k-1]=snake[k];
    			}
    			
    		} else if (keyevent.type == SDL_QUIT) {
    			exit(0);
    		}
    		
    	}
    
    		
    		SDL_Flip(screen);
    }
    
    void collision(){
    	int i;
    // Walls
    	if((snake[snake_length-1].row>maxrow-2) || (snake[snake_length-1].row<1) 
    		|| (snake[snake_length-1].col>maxcol-2) || (snake[snake_length-1].col<1)
    // Obstacle
    		|| (grid[snake[snake_length-1].row][snake[snake_length-1].col] == 'o')){
    		exit(0);
    		}
    // Snake
    	for(i=0;i<snake_length-1;i++){
    		if((snake[snake_length-1].row == snake[i].row) &&
    			(snake[snake_length-1].col == snake[i].col)){
    				exit(0);
    		}
    	}
    // Food
    	if(grid[snake[snake_length-1].row][snake[snake_length-1].col] == 'f'){
    	 snake_length=snake_length+1;
    	 }
    }
    I added the collision function and added to the make_move function but am not sure why when i pick up the food the snake length does not increase. I am not going to completely finish this by tommorow but I want to at least implement the food eating.

  5. #5
    Registered User
    Join Date
    Apr 2013
    Posts
    3
    Also thank you very much for the help everybody I am new to Programming and can use all the help I can get

  6. #6
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    Code:
        if(grid[snake[snake_length-1].row][snake[snake_length-1].col] == 'f'){
         snake_length=snake_length+1;
         }
    But you also need to set
    snake[x].row =
    snake[x].col =
    to some meaningful position on screen (not just leave it at 0,0)
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with a snake game?
    By awr7126 in forum Game Programming
    Replies: 2
    Last Post: 12-06-2010, 06:39 PM
  2. C++ snake
    By nwasiq in forum C++ Programming
    Replies: 10
    Last Post: 11-20-2010, 11:35 AM
  3. Snake
    By Grantyt3 in forum Game Programming
    Replies: 2
    Last Post: 05-24-2006, 01:35 PM
  4. My snake
    By vasanth in forum A Brief History of Cprogramming.com
    Replies: 32
    Last Post: 06-07-2002, 04:45 AM
  5. My new advanced Snake
    By vasanth in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 05-28-2002, 03:51 AM