Adding Collision to Python Game

Adding Collision to Python Game

Postby Indiiyana » Tue Nov 26, 2013 1:57 am

Hello,

I don't suppose anyone could help me putting in collision so that if the Snake collides with itself or hits the borders of the window, then the player loses the game? This is the code:
Code: Select all
from random import randint
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *

window = 0
width, height = 500, 500
field_width, field_height = 50, 50
snake = [(20, 20)]
food = []
snake_dir = (1, 0)
interval = 200

def refresh2d_custom(width, height, internal_width, internal_height):
    glViewport(0, 0, width, height)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    glOrtho(0.0, internal_width, 0.0, internal_height, 0.0, 1.0)
    glMatrixMode (GL_MODELVIEW)
    glLoadIdentity()
   
def vec_add((x1, y1), (x2, y2)):
    return (x1 + x2, y1 + y2)
   
def update(value):   
    snake.insert(0, vec_add(snake[0], snake_dir))      # insert new position in the beginning of the snake list
    snake.pop()                                        # remove the last element
 
    r = randint(0, 20)                                 # spawn food with 5% chance
    if r == 0:
        x, y = randint(0, field_width), randint(0, field_height) # random spawn pos
        food.append((x, y))
 
    glutTimerFunc(interval, update, 0)
   
    (hx, hy) = snake[0]
    for x, y in food:
        if hx == x and hy == y:
            snake.append((x, y))
            food.remove((x, y))
   
def keyboard(*args):
    global snake_dir
   
    if args[0] == 'w':
        snake_dir = (0,1)
    if args[0] == 's':
        snake_dir = (0, -1)
    if args[0] == 'a':
        snake_dir = (-1, 0)
    if args[0] == 'd':
        snake_dir = (1, 0)
   
def draw_rect(x, y, width, height):
    glBegin(GL_QUADS)
    glVertex2f(x, y)
    glVertex2f(x + width, y)
    glVertex2f(x + width, y + height)
    glVertex2f(x, y + height)

   
def draw_snake():
    glColor3f(1.0, 1.0, 1.0)
    for x, y in snake:
        draw_rect(x, y, 1, 1)
       
def draw_food():
    glColor3f(0.5, 0.5, 1.0)
    for x, y in food:
        draw_rect(x, y, 1, 1)
   
def draw():
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    glLoadIdentity()
    refresh2d_custom(width, height, field_width, field_height)
   
    draw_food()
    draw_snake()
   
    glutSwapBuffers()
   
# initalize
glutInit()
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH)
glutInitWindowSize(width, height)
glutInitWindowPosition(0, 0)
window = glutCreateWindow("SNAKE")
glutDisplayFunc(draw)
glutIdleFunc(draw)
glutTimerFunc(interval, update, 0)
glutKeyboardFunc(keyboard)
glutMainLoop()


Much obliged.
Last edited by micseydel on Tue Nov 26, 2013 1:58 am, edited 1 time in total.
Reason: Locked OP.
Indiiyana
 
Posts: 10
Joined: Tue Nov 26, 2013 1:55 am

Re: Adding Collision to Python Game

Postby Mekire » Tue Nov 26, 2013 5:17 am

Since you are using a list to represent the cells of the player snake, why not just use the in operator to check if the snake already contains a cell before you try to insert it. If it does, you are dead. Similarly you can create a list to represent the cells occupied by obstacles like the border and even interior-level walls. If the snake trys to add one of those cells during the update phase, you're dead. I'm not at a computer I can code on at the moment and I am not familiar with the specifics of GLUT (you should really use pygame with openGL or Pyglet, although honestly this doesn't require openGL at all), but this shouldn't be hard.

I'll try to write it up later if you haven't got it figured.
-Mek
User avatar
Mekire
 
Posts: 1025
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Re: Adding Collision to Python Game

Postby Indiiyana » Wed Nov 27, 2013 12:30 am

Gah, I hate to say that I give up but I think I must say it: "I give up."

I haven't heard of the "in" operator before, I had a look on Google and I did put this down:
Code: Select all
def snake_die(snake):
    if snake in snake:
        print "You are dead."


I know it's wrong though...
Indiiyana
 
Posts: 10
Joined: Tue Nov 26, 2013 1:55 am

Re: Adding Collision to Python Game

Postby Mekire » Wed Nov 27, 2013 1:49 am

This appears to be where you add cells to the snake:
Code: Select all
def update(value):   
    snake.insert(0, vec_add(snake[0], snake_dir))      # insert new position in the beginning of the snake list

Just change it so that it checks if the snake already has that cell before adding.

Something like this:
Code: Select all
def update(value):
    next_cell = vec_add(snake[0], snake_dir)
    if next_cell in snake:
        #You are dead.
    else:
        snake.insert(0,next_cell) 

On another note, you should really avoid global variables.

Anyway, Untested; let me know if you make progress.
-Mek
User avatar
Mekire
 
Posts: 1025
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Re: Adding Collision to Python Game

Postby Indiiyana » Wed Nov 27, 2013 11:28 pm

Aye that bit worked, however is it possible to output something like a popup box to say "You are dead." and then making the game restart?

Also, these 0s are mentioned around the code, but I'm not sure what they mean (I followed a tutorial on the Internet for this game):
Code: Select all
snake.insert(0, next_cell)


What does that 0 mean? I have a feeling it's to do with "value."

Thank you, by the way :D.
Indiiyana
 
Posts: 10
Joined: Tue Nov 26, 2013 1:55 am

Re: Adding Collision to Python Game

Postby Mekire » Thu Nov 28, 2013 7:46 am

Ahh, I see; you didn't write this. Mentioning that would have helped.

The zero in the insert line is the location in the list to insert the value. In this case you are putting the value at the very front of the list (the zero index).

As for rendering a message to the screen on game over; certainly this is possible. I'm afraid however I am not familiar enough with GLUT or openGL to really help you. I still suggest you leave openGL alone for now until you are more comfortable with python in general.

-Mek
User avatar
Mekire
 
Posts: 1025
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Re: Adding Collision to Python Game

Postby Indiiyana » Wed Jan 15, 2014 8:43 am

I know it's a couple of months late but I just wanted to say thanks, so, thanks!
Indiiyana
 
Posts: 10
Joined: Tue Nov 26, 2013 1:55 am


Return to Game Development

Who is online

Users browsing this forum: W3C [Linkcheck] and 1 guest