Go Back   CodingForums.com > :: Server side development > Other server side languages/ issues > Python

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 12-11-2011, 05:57 PM   PM User | #1
karlrais
New to the CF scene

 
Join Date: Dec 2011
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
karlrais is an unknown quantity at this point
Need some help with Snake game

Code:
import random
from tkinter import *


    

def Käsud(käsk):
    canvas = käsk.widget.canvas
    canvas.data["JärgmiseKäsuEiramine"] = True # for better timing
    # first process keys that work even if the game is over
    if (käsk.char == "q"):
        gameOver(canvas)
    elif (käsk.char == "r"):
        init(canvas)

    # now process keys that only work if the game is not over
    if (canvas.data["GameOver"] == False):
        if (käsk.keysym == "Up"):
            moveSnake(canvas, -1, 0)
        elif (käsk.keysym == "Down"):
            moveSnake(canvas, +1, 0)
        elif (käsk.keysym == "Left"):
            moveSnake(canvas, 0,-1)
        elif (käsk.keysym == "Right"):
            moveSnake(canvas, 0,+1)
    redrawAll(canvas)


from math import fmod

def moveSnake(canvas, rida, veerg):
    # move the snake one step forward in the given direction.
    k1 = canvas.data["snakeDrow"]
    k2 = canvas.data["snakeDcol"]
    if k1 != 0 and rida != 0 or k2!=0 and veerg!=0:
        rida = k1
        veerg = k2
    canvas.data["snakeDrow"] = rida # store direction for next timer event
    canvas.data["snakeDcol"] = veerg
    snakeBoard = canvas.data["snakeBoard"]
    read = len(snakeBoard)
    veerud = len(snakeBoard[0])
    headRow = canvas.data["headRow"]
    headCol = canvas.data["headCol"]
    newHeadRow = headRow + rida
    
    newHeadRow = int(fmod(newHeadRow,read))
    if rida == -1 and newHeadRow < 0:
        newHeadRow = read-1
    newHeadCol = headCol + veerg
    newHeadCol = int(fmod(newHeadCol,veerud))
    if veerg == -1 and newHeadCol < 0:
        newHeadCol = veerud -1
        
    if (snakeBoard[newHeadRow][newHeadCol] > 0) :
        # snake ran into itself!
        gameOver(canvas)
    elif (snakeBoard[newHeadRow][newHeadCol] < 0):
        # eating food!  Yum!
        snakeBoard[newHeadRow][newHeadCol] = 1 + snakeBoard[headRow][headCol];
        canvas.data["headRow"] = newHeadRow
        canvas.data["headCol"] = newHeadCol
        placeFood(canvas)
    else:
        # normal move forward (not eating food)
        snakeBoard[newHeadRow][newHeadCol] = 1 + snakeBoard[headRow][headCol];
        canvas.data["headRow"] = newHeadRow
        canvas.data["headCol"] = newHeadCol
        removeTail(canvas)

def removeTail(canvas):
    # find every snake cell and subtract 1 from it.  When we're done,
    # the old tail (which was 1) will become 0, so will not be part of the snake.
    # So the snake shrinks by 1 value, the tail.
    snakeBoard = canvas.data["snakeBoard"]
    rows = len(snakeBoard)
    cols = len(snakeBoard[0])
    for row in range(rows):
        for col in range(cols):
            if (snakeBoard[row][col] > 0):
                snakeBoard[row][col] -= 1

def gameOver(canvas):
    canvas.data["GameOver"] = True

def timerFired(canvas):
    JärgmiseKäsuEiramine = canvas.data["JärgmiseKäsuEiramine"]
    canvas.data["JärgmiseKäsuEiramine"] = False
    if ((canvas.data["GameOver"] == False) and
        (JärgmiseKäsuEiramine == False)):
        # only process timerFired if game is not over
        drow = canvas.data["snakeDrow"]
        dcol = canvas.data["snakeDcol"]
        moveSnake(canvas, drow, dcol)
        redrawAll(canvas)
    # whether or not game is over, call next timerFired
    # (or we'll never call timerFired again!)
    delay = 200 # milliseconds
    canvas.after(delay, timerFired, canvas) # pause, then call timerFired again

def redrawAll(canvas):
    canvas.delete(ALL)
    drawSnakeBoard(canvas)
    if (canvas.data["GameOver"] == True):
        cx = canvas.data["canvasWidth"]/2
        cy = canvas.data["canvasHeight"]/2
        canvas.create_text(cx, cy, text="Game Over!", font=("Helvetica", 32, "bold"))

def drawSnakeBoard(canvas):
    snakeBoard = canvas.data["snakeBoard"]
    rows = len(snakeBoard)
    cols = len(snakeBoard[0])
    head = False
    for row in range(rows):
        for col in range(cols):
            head = drawSnakeCell(canvas, snakeBoard, row, col, head)
    
def drawSnakeCell(canvas, snakeBoard, row, col, head):
    serv = canvas.data["serv"]
    cellSize = canvas.data["cellSize"]
    left = serv + col * cellSize
    right = left + cellSize
    top = serv + row * cellSize
    bottom = top + cellSize
    juku = PhotoImage(file="mercurypea.gif")
    #canvas.create_rectangle(left, top, right, bottom, fill="white")
    if (snakeBoard[row][col] > 0) :
        # draw part of the snake body
        canvas.create_polygon((left+10,top),(left,top),(right,bottom+10),(right, bottom))
        canvas.create_image(left, top, image=juku)
        head = True
    elif (snakeBoard[row][col] < 0):
        # draw food
        canvas.create_oval(left, top, right, bottom, fill="red")
    return head
    

def loadSnakeBoard(canvas):
    rows = canvas.data["rows"]
    cols = canvas.data["cols"]
    snakeBoard = [ ]
    for row in range(rows): snakeBoard += [[0] * cols]
    snakeBoard[int(rows/2)][int(cols/2)] = 1
    canvas.data["snakeBoard"] = snakeBoard
    findSnakeHead(canvas)
    placeFood(canvas)

def placeFood(canvas):
    # place food (-1) in a random location on the snakeBoard, but
    # keep picking random locations until we find one that is not
    # part of the snake!
    snakeBoard = canvas.data["snakeBoard"]
    rows = len(snakeBoard)
    cols = len(snakeBoard[0])
    while True:
        row = random.randint(0,rows-1)
        col = random.randint(0,cols-1)
        if (snakeBoard[row][col] == 0):
            break
    snakeBoard[row][col] = -1

def findSnakeHead(canvas):
    # find where snakeBoard[row][col] is largest, and
    # store this location in headRow, headCol
    snakeBoard = canvas.data["snakeBoard"]
    rows = len(snakeBoard)
    cols = len(snakeBoard[0])
    headRow = 0
    headCol = 0
    for row in range(rows):
        for col in range(cols):
            if (snakeBoard[row][col] > snakeBoard[headRow][headCol]):
                headRow = row
                headCol = col
    canvas.data["headRow"] = headRow
    canvas.data["headCol"] = headCol

def printInstructions():
    print("Snake")
    print("Kasuta noole nuppe, et ussi liikumist kontrollida.")
    print("Söö toitu, et kasvada.")
    print("Läbi seina ei saa minna!")
    print("There is a Justin Bieber inside every part of the snake and you know what happens if you run into Justin Bieber, YOU DIE!")
    print("Vajuta 'r', et mängu uuesti alustada.")
    print("Vajuta 'q', et lõpetada.")

def init(canvas):
    printInstructions()
    loadSnakeBoard(canvas)
    canvas.data["GameOver"] = False
    canvas.data["snakeDrow"] = 0
    canvas.data["snakeDcol"] = -1 # start moving left
    canvas.data["JärgmiseKäsuEiramine"] = False
    redrawAll(canvas)

########### copy-paste below here ###########

def run(read,veerud):
    # create the root and the canvas
    root = Tk()
    serv = 10
    cellSize = 30
    canvasWidth = 2*serv + veerud*cellSize
    canvasHeight = 2*serv + read*cellSize
    canvas = Canvas(root, width=canvasWidth, height=canvasHeight)
    canvas.pack()
    root.resizable(width=0, height=0)
    # Store canvas in root and in canvas itself for callbacks
    root.canvas = canvas.canvas = canvas
    # Set up canvas data and call init
    canvas.data = { }
    canvas.data["serv"] = serv
    canvas.data["cellSize"] = cellSize
    canvas.data["canvasWidth"] = canvasWidth
    canvas.data["canvasHeight"] = canvasHeight
    canvas.data["rows"] = read
    canvas.data["cols"] = veerud
    init(canvas)
    # set up events
    root.bind("<Button-1>")
    root.bind("<Key>", Käsud)
    timerFired(canvas)
    # and launch the app
    root.mainloop()  # This call BLOCKS (so your program waits until you close the window!)

run(10,15)

Part that we need help with:

Code:
def drawSnakeCell(canvas, snakeBoard, row, col, head):
    serv = canvas.data["serv"]
    cellSize = canvas.data["cellSize"]
    left = serv + col * cellSize
    right = left + cellSize
    top = serv + row * cellSize
    bottom = top + cellSize
    juku = PhotoImage(file="mercurypea.gif")
    #canvas.create_rectangle(left, top, right, bottom, fill="white")
    if (snakeBoard[row][col] > 0) :
        # draw part of the snake body
        canvas.create_polygon((left+10,top),(left,top),(right,bottom+10),(right, bottom))
        canvas.create_image(left, top, image=juku)
        head = True
    elif (snakeBoard[row][col] < 0):
        # draw food
        canvas.create_oval(left, top, right, bottom, fill="red")
    return head

We want the Snake head to look like the picture we want (Freddy Mercury and the food would look like Bieber, yea I know we are evil). But the head keeps dissapearing.
karlrais is offline   Reply With Quote
Old 12-12-2011, 02:02 AM   PM User | #2
Apothem
Regular Coder

 
Apothem's Avatar
 
Join Date: Mar 2008
Posts: 380
Thanks: 36
Thanked 25 Times in 25 Posts
Apothem is an unknown quantity at this point
Can you figure out when the head disappears?

One thing that I think may be wrong is that you have an infeasible path for when snakeBoard[row][col] is equal to 0.
Apothem is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 09:10 PM.


Advertisement
Log in to turn off these ads.