10 Replies - 2244 Views - Last Post: 10 August 2012 - 08:03 AM Rate Topic: -----

#1 pacgcrosss  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 08-August 12

control bug for tron bike game using Tkinter

Posted 08 August 2012 - 06:40 PM

Hi all,

I'm making a simple game in python using Tkinter. The game is the tron bike game which, if you are not familiar with, the point is to destroy the other bike by making it cross your path. I had it all working fine with just one bike. However, when I tried to add another bike to be controlled by another playing using the same keyboard I had a control issue where moving one bike moves both. I thought it would be very easy to add another bike using the same method as I did for the first, but as you can see I'm having problems. Maybe someone knows a better way to tackle the multiplayer element? It might be a very simple fix but it's escaping me right now.

import random
from Tkinter import *

def mousePressed(event):
    redrawAll()

def keyPressed(event):
    canvas.data.ignoreNextTimerEvent = True 
    if (event.char == "q"):
        gameOver()
    elif (event.char == "r"):
        init()
    elif (event.char == "d"):
        canvas.data.inDebugMode = not canvas.data.inDebugMode
    if (canvas.data.isGameOver == False):
        if (event.keysym == "Up"):
            moveBike(-1, 0)
        elif (event.keysym == "Down"):
            moveBike(+1, 0)
        elif (event.keysym == "Left"):
            moveBike(0,-1)
        elif (event.keysym == "Right"):
            moveBike(0,+1)
        elif (event.keysym == "a"):
            moveBike2(0,-1)
        elif (event.keysym == "s"):
            moveBike2(+1,0)
        elif (event.keysym == "w"):
            moveBike2(-1,0)
        #elif (event.keysym == "d"):
            moveBike2(0, +1)
    redrawAll()
    
def moveBike2(drow, dcol):
    canvas.data.bike2Drow = drow 
    canvas.data.bike2Dcol = dcol
    tronBoard = canvas.data.tronBoard
    rows = len(tronBoard)
    cols = len(tronBoard[0])
    bike2Row = canvas.data.bike2Row
    bike2Col = canvas.data.bike2Col
    newBike2Row = bike2Row + drow
    newBike2Col = bike2Col + dcol
    canvas.data.path2.append((newBike2Row, newBike2Col))
    if ((newBike2Row < 0) or (newBike2Row >= rows) or
        (newBike2Col < 0) or (newBike2Col >= cols)):
        gameOver()
    elif (tronBoard[newBike2Row][newBike2Col] > 0):
        gameOver()
    elif (tronBoard[newBike2Row][newBike2Col] == 0):
        tronBoard[newBike2Row][newBike2Col] = tronBoard[bike2Row][bike2Col] - 1
        canvas.data.bike2Row = newBike2Row
        canvas.data.bike2Col = newBike2Col
##    else:
##        tronBoard[newBike2Row][newBike2Col] = 1 + tronBoard[bike2Row][bike2Col]
##        canvas.data.bike2Row = newBike2Row
##        canvas.data.bike2Col = newBike2Col
        
def moveBike(drow, dcol):
    canvas.data.bikeDrow = drow 
    canvas.data.bikeDcol = dcol
    tronBoard = canvas.data.tronBoard
    rows = len(tronBoard)
    cols = len(tronBoard[0])
    bikeRow = canvas.data.bikeRow
    bikeCol = canvas.data.bikeCol
    newBikeRow = bikeRow + drow
    newBikeCol = bikeCol + dcol
    canvas.data.path1.append((newBikeRow, newBikeCol))
    if ((newBikeRow < 0) or (newBikeRow >= rows) or
        (newBikeCol < 0) or (newBikeCol >= cols)):
        gameOver()
    elif (tronBoard[newBikeRow][newBikeCol] > 0):
        gameOver()
    elif (tronBoard[newBikeRow][newBikeCol] == 0):
        tronBoard[newBikeRow][newBikeCol] = 1 + tronBoard[bikeRow][bikeCol];
        canvas.data.bikeRow = newBikeRow
        canvas.data.bikeCol = newBikeCol
##    else:
##        tronBoard[newBikeRow][newBikeCol] = 1 + tronBoard[bikeRow][bikeCol];
##        canvas.data.bikeRow = newBikeRow
##        canvas.data.bikeCol = newBikeCol
        #removeTail()



def gameOver():
    canvas.data.isGameOver = True

def timerFired():
    tronBoard = canvas.data.tronBoard
    ignoreThisTimerEvent = canvas.data.ignoreNextTimerEvent
    canvas.data.ignoreNextTimerEvent = False
    if ((canvas.data.isGameOver == False) and
        (ignoreThisTimerEvent == False)):
        drow = canvas.data.bikeDrow
        dcol = canvas.data.bikeDcol
        moveBike(drow, dcol)
        moveBike2(drow, dcol)
        redrawAll()
    delay = 50
    drawBikePath()
    drawBike2Path()
    print tronBoard[canvas.data.bike2Row][canvas.data.bike2Col]
    canvas.after(delay, timerFired)


    

def redrawAll():
    #drawBikePath1()
    cx = canvas.data.canvasWidth/2
    cy = canvas.data.canvasHeight/2
    if (canvas.data.isGameOver == True):
        canvas.create_text(cx, cy, text="Game Over!", fill = "red",
                           font=("Helvetica", 32, "bold"))
    



def drawBikePath():
    row,col = canvas.data.path1[-1]
    margin = canvas.data.margin
    cellSize = canvas.data.cellSize
    left = margin + col *cellSize
    right = left + cellSize
    top = margin + row*cellSize
    bottom = top + cellSize
    canvas.create_rectangle(left, top, right, bottom, fill="green")

def drawBike2Path():
    row,col = canvas.data.path2[-1]
    margin = canvas.data.margin
    cellSize = canvas.data.cellSize
    left = margin + col *cellSize
    right = left + cellSize
    top = margin + row*cellSize
    bottom = top + cellSize
    canvas.create_rectangle(left, top, right, bottom, fill="purple")
        
def drawTronBoard():
    tronBoard = canvas.data.tronBoard
    rows = len(tronBoard)
    cols = len(tronBoard[0])
    for row in range(rows):
        for col in range(cols):
            drawTronCell(tronBoard, row, col)

def drawTronCell(tronBoard, row, col):
    margin = canvas.data.margin
    cellSize = canvas.data.cellSize
    bikeRow = canvas.data.bikeRow
    bikeCol = canvas.data.bikeCol
    left = margin + col * cellSize
    right = left + cellSize
    top = margin + row * cellSize
    bottom = top + cellSize
    canvas.create_rectangle(left, top, right, bottom, fill="black", outline="brown")
    if (tronBoard[row][col] > 0):
        canvas.create_rectangle(left, top, right, bottom, fill="green")
##    elif (tronBoard[row][col] < 0):
##        canvas.create_rectangle(left, top, right, bottom, fill="green")
##    if (tronBoard[row][col]==tronBoard[bikeRow][bikeCol]):
##        canvas.create_rectangle(left, top, right, bottom, fill = "purple")
    if (canvas.data.inDebugMode == True):
        canvas.create_text(left+cellSize/2,top+cellSize/2,
                           text=str(tronBoard[row][col]),font=("Helvatica", 14, "bold"))

def loadTronBoard():
    rows = canvas.data.rows
    cols = canvas.data.cols
    tronBoard = [ ]
    for row in range(rows): tronBoard += [[0] * cols]
    tronBoard[rows/2][cols/8] = 1
    tronBoard[rows/2][cols-cols/8] = -1
    canvas.data.tronBoard = tronBoard
    findBike()
    findBike2()
    #placeBoost()

def placeBoost():
    tronBoard = canvas.data.tronBoard
    rows = len(tronBoard)
    cols = len(tronBoard[0])
    while True:
        row = random.randint(0,rows-1)
        col = random.randint(0,cols-1)
        if (tronBoard[row][col] == 0):
            break
    tronBoard[row][col] = -1

def findBike():
    tronBoard = canvas.data.tronBoard
    rows = len(tronBoard)
    cols = len(tronBoard[0])
    bikeRow = 0
    bikeCol = 0
    for row in range(rows):
        for col in range(cols):
            if (tronBoard[row][col] > tronBoard[bikeRow][bikeCol]):
                bikeRow = row
                bikeCol = col
    canvas.data.bikeRow = bikeRow
    canvas.data.bikeCol = bikeCol

def findBike2():
    tronBoard = canvas.data.tronBoard
    rows = len(tronBoard)
    cols = len(tronBoard[0])
    bike2Row = 0
    bike2Col = 0
    for row in range(rows):
        for col in range(cols):
            if (tronBoard[row][col] < tronBoard[bike2Row][bike2Col]):
                bike2Row = row
                bike2Col = col
    canvas.data.bike2Row = bike2Row
    canvas.data.bike2Col = bike2Col

def printInstructions():
    print "Press 'd' for debug mode."
    print "Press 'r' to restart."

def init():
    printInstructions()
    loadTronBoard()
    canvas.data.inDebugMode = False
    canvas.data.isGameOver = False
    canvas.data.path1 = []
    canvas.data.path2 = []
    canvas.data.bikeDrow = +1
    canvas.data.bikeDcol = 0
    canvas.data.bike2Drow = -1
    canvas.data.bike2Dcol = 0
    canvas.data.ignoreNextTimerEvent = False
    drawTronBoard()
    redrawAll()

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

def run(rows, cols):
    # create the root and the canvas
    global canvas
    root = Tk()
    margin = 5
    cellSize = 15
    canvasWidth = 2*margin + cols*cellSize
    canvasHeight = 2*margin + rows*cellSize
    canvas = Canvas(root, width=canvasWidth, height=canvasHeight)
    canvas.pack()
    # Store canvas in root and in canvas itself for callbacks
    root.canvas = canvas.canvas = canvas
    # Set up canvas data and call init
    class Struct: pass
    canvas.data = Struct()
    canvas.data.margin = margin
    canvas.data.cellSize = cellSize
    canvas.data.canvasWidth = canvasWidth
    canvas.data.canvasHeight = canvasHeight
    canvas.data.rows = rows
    canvas.data.cols = cols
    init()
    # set up events
    root.bind("<Button-1>", mousePressed)
    root.bind("<Key>", keyPressed)
    timerFired()
    # and launch the app
    root.mainloop()  # This call BLOCKS (so your program waits until you close the window!)

run(40,40)



Is This A Good Question/Topic? 0
  • +

Replies To: control bug for tron bike game using Tkinter

#2 atraub  Icon User is offline

  • Pythoneer
  • member icon

Reputation: 756
  • View blog
  • Posts: 1,990
  • Joined: 23-December 08

Re: control bug for tron bike game using Tkinter

Posted 08 August 2012 - 07:17 PM

I'm very impressed with this program, I'm working on locating your bug as we speak.
Was This Post Helpful? 0
  • +
  • -

#3 pacgcrosss  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 08-August 12

Re: control bug for tron bike game using Tkinter

Posted 08 August 2012 - 07:26 PM

View Postatraub, on 08 August 2012 - 07:17 PM, said:

I'm very impressed with this program, I'm working on locating your bug as we speak.


thanks a lot! i appreciate it
Was This Post Helpful? 0
  • +
  • -

#4 pacgcrosss  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 08-August 12

Re: control bug for tron bike game using Tkinter

Posted 09 August 2012 - 08:32 AM

has anybody had any luck with this?
Was This Post Helpful? 0
  • +
  • -

#5 atraub  Icon User is offline

  • Pythoneer
  • member icon

Reputation: 756
  • View blog
  • Posts: 1,990
  • Joined: 23-December 08

Re: control bug for tron bike game using Tkinter

Posted 09 August 2012 - 10:37 AM

not yet, your style of doing it is a little different from what I'm use to. It's taking some time, and on top of that, I work during the day, so it'll be a bit longer on my end.
Was This Post Helpful? 0
  • +
  • -

#6 pacgcrosss  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 08-August 12

Re: control bug for tron bike game using Tkinter

Posted 09 August 2012 - 12:54 PM

ah ok, thats understandable. I should mention that I'm supposed to have this figured out by midnight tonight eastern time
Was This Post Helpful? 0
  • +
  • -

#7 atraub  Icon User is offline

  • Pythoneer
  • member icon

Reputation: 756
  • View blog
  • Posts: 1,990
  • Joined: 23-December 08

Re: control bug for tron bike game using Tkinter

Posted 09 August 2012 - 06:06 PM

why the time limit?
Was This Post Helpful? 0
  • +
  • -

#8 pacgcrosss  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 08-August 12

Re: control bug for tron bike game using Tkinter

Posted 09 August 2012 - 06:10 PM

I actually just fixed my issue, thanks though. I'll post the full working game later tonight.
Was This Post Helpful? 0
  • +
  • -

#9 atraub  Icon User is offline

  • Pythoneer
  • member icon

Reputation: 756
  • View blog
  • Posts: 1,990
  • Joined: 23-December 08

Re: control bug for tron bike game using Tkinter

Posted 09 August 2012 - 06:22 PM

I look forward to seeing it!
Was This Post Helpful? 0
  • +
  • -

#10 pacgcrosss  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 08-August 12

Re: control bug for tron bike game using Tkinter

Posted 09 August 2012 - 09:34 PM

kind of hard to play by yourself haha but here it is:
#TRON

import random
from Tkinter import *

def keyPressed(event):
    if event.keysym == "Return":
        canvas.data.inGame = True
    if (event.char == "q"):
        gameOver()
    elif (event.char == "r"):
        init()
    if (canvas.data.isGameOver == False):
        if (event.keysym == "Up"):
            moveBike(-1, 0)
        elif (event.keysym == "Down"):
            moveBike(+1, 0)
        elif (event.keysym == "Left"):
            moveBike(0,-1)
        elif (event.keysym == "Right"):
            moveBike(0,+1)
        elif (event.keysym == "a"):
            moveBike2(0,-1)
        elif (event.keysym == "s"):
            moveBike2(+1,0)
        elif (event.keysym == "w"):
            moveBike2(-1,0)
        elif (event.keysym == "d"):
            moveBike2(0, +1)
    
def moveBike2(d2row, d2col):
    canvas.data.bike2Drow = d2row 
    canvas.data.bike2Dcol = d2col
    tronBoard = canvas.data.tronBoard
    rows = len(tronBoard)
    cols = len(tronBoard[0])
    bike2Row = canvas.data.bike2Row
    bike2Col = canvas.data.bike2Col
    newBike2Row = bike2Row + d2row
    newBike2Col = bike2Col + d2col
    if ((newBike2Row < 0) or (newBike2Row >= rows) or
        (newBike2Col < 0) or (newBike2Col >= cols)):
        canvas.data.player1Score+=1
        canvas.data.loser = 2
        gameOver()
    elif (tronBoard[newBike2Row][newBike2Col] != 0):
        canvas.data.player2Score+=1
        canvas.data.loser = 2
        gameOver()
    elif (tronBoard[newBike2Row][newBike2Col] == 0):
        tronBoard[newBike2Row][newBike2Col] = tronBoard[bike2Row][bike2Col] - 1
        canvas.data.bike2Row = newBike2Row
        canvas.data.bike2Col = newBike2Col
        canvas.data.path2.append((newBike2Row, newBike2Col))
        
def moveBike(drow, dcol):
    canvas.data.bikeDrow = drow 
    canvas.data.bikeDcol = dcol
    tronBoard = canvas.data.tronBoard
    rows = len(tronBoard)
    cols = len(tronBoard[0])
    bikeRow = canvas.data.bikeRow
    bikeCol = canvas.data.bikeCol
    newBikeRow = bikeRow + drow
    newBikeCol = bikeCol + dcol    
    if ((newBikeRow < 0) or (newBikeRow >= rows) or
        (newBikeCol < 0) or (newBikeCol >= cols)):
        canvas.data.player2Score+=1
        canvas.data.loser = 1
        gameOver()
    elif (tronBoard[newBikeRow][newBikeCol] != 0):
        canvas.data.player2Score+=1
        canvas.data.loser = 1
        gameOver()
    elif (tronBoard[newBikeRow][newBikeCol] == 0):
        tronBoard[newBikeRow][newBikeCol] = 1 + tronBoard[bikeRow][bikeCol];
        canvas.data.bikeRow = newBikeRow
        canvas.data.bikeCol = newBikeCol
        canvas.data.path1.append((newBikeRow, newBikeCol))



def gameOver():
    cx = canvas.data.canvasWidth/2
    cy = canvas.data.canvasHeight/2
    if canvas.data.loser==1:
         canvas.create_text(cx, cy, text="Player 2 Wins!", fill = "brown",
                           font=("Helvetica", 32, "bold"))
    if canvas.data.loser==2:
         canvas.create_text(cx, cy, text="Player 1 Wins!", fill = "brown",
                           font=("Helvetica", 32, "bold"))
    canvas.data.isGameOver = True

def timerFired():
    if canvas.data.inGame == True:
        tronBoard = canvas.data.tronBoard
        ignoreThisTimerEvent = canvas.data.ignoreNextTimerEvent
        canvas.data.ignoreNextTimerEvent = False
        if ((canvas.data.isGameOver == False) and
            (ignoreThisTimerEvent == False)):
            drow = canvas.data.bikeDrow
            dcol = canvas.data.bikeDcol
            d2row = canvas.data.bike2Drow
            d2col = canvas.data.bike2Dcol
            moveBike(drow, dcol)
            moveBike2(d2row, d2col)
            drawBikePath()
            drawBike2Path()
        
        
    delay = 50
    canvas.after(delay, timerFired)

def drawBikePath():
    row,col = canvas.data.path1[-1]
    margin = canvas.data.margin
    cellSize = canvas.data.cellSize
    left = margin + col *cellSize
    right = left + cellSize
    top = margin + row*cellSize
    bottom = top + cellSize
    canvas.create_rectangle(left, top, right, bottom, fill="lime green")
    if len(canvas.data.path1)>=2:
        row, col = canvas.data.path1[-2]
        cellSize = canvas.data.cellSize
        left = margin + col *cellSize
        right = left + cellSize
        top = margin + row*cellSize
        bottom = top + cellSize
        canvas.create_rectangle(left, top, right, bottom, fill="dark green")

def drawBike2Path():
    row,col = canvas.data.path2[-1]
    margin = canvas.data.margin
    cellSize = canvas.data.cellSize
    left = margin + col *cellSize
    right = left + cellSize
    top = margin + row*cellSize
    bottom = top + cellSize
    canvas.create_rectangle(left, top, right, bottom, fill="violet")
    if len(canvas.data.path2)>=2:
        row, col = canvas.data.path2[-2]
        cellSize = canvas.data.cellSize
        left = margin + col *cellSize
        right = left + cellSize
        top = margin + row*cellSize
        bottom = top + cellSize
        canvas.create_rectangle(left, top, right, bottom, fill="dark violet")
        
def drawTronBoard():
    tronBoard = canvas.data.tronBoard
    rows = len(tronBoard)
    cols = len(tronBoard[0])
    for row in range(rows):
        for col in range(cols):
            drawTronCell(tronBoard, row, col)

def drawTronCell(tronBoard, row, col):
    margin = canvas.data.margin
    cellSize = canvas.data.cellSize
    bikeRow = canvas.data.bikeRow
    bikeCol = canvas.data.bikeCol
    left = margin + col * cellSize
    right = left + cellSize
    top = margin + row * cellSize
    bottom = top + cellSize
    canvas.create_rectangle(left, top, right, bottom, fill="black", outline="brown")

def loadTronBoard():
    rows = canvas.data.rows
    cols = canvas.data.cols
    tronBoard = [ ]
    for row in range(rows): tronBoard += [[0] * cols]
    #player1 start position
    tronBoard[rows/2][cols/8] = 1
    #player2 start position
    tronBoard[rows/2][cols-cols/8] = -1
    canvas.data.tronBoard = tronBoard
    findBike()
    findBike2()   

def placeBoost():
    tronBoard = canvas.data.tronBoard
    rows = len(tronBoard)
    cols = len(tronBoard[0])
    while True:
        row = random.randint(0,rows-1)
        col = random.randint(0,cols-1)
        if (tronBoard[row][col] == 0):
            break
    tronBoard[row][col] = -1

def findBike():
    tronBoard = canvas.data.tronBoard
    rows = len(tronBoard)
    cols = len(tronBoard[0])
    bikeRow = 0
    bikeCol = 0
    for row in range(rows):
        for col in range(cols):
            if (tronBoard[row][col] > tronBoard[bikeRow][bikeCol]):
                bikeRow = row
                bikeCol = col
    canvas.data.bikeRow = bikeRow
    canvas.data.bikeCol = bikeCol

def findBike2():
    tronBoard = canvas.data.tronBoard
    rows = len(tronBoard)
    cols = len(tronBoard[0])
    bike2Row = 0
    bike2Col = 0
    for row in range(rows):
        for col in range(cols):
            if (tronBoard[row][col] < tronBoard[bike2Row][bike2Col]):
                bike2Row = row
                bike2Col = col
    canvas.data.bike2Row = bike2Row
    canvas.data.bike2Col = bike2Col


def init():
    loadTronBoard()
    canvas.data.inDebugMode = False
    canvas.data.isGameOver = False
    canvas.data.path1 = []
    canvas.data.path2 = []
    canvas.data.loser = 0
    canvasWidth = canvas.data.canvasWidth
    canvasHeight = canvas.data.canvasHeight
    canvas.data.bikeDrow = +1
    canvas.data.bikeDcol = 0
    canvas.data.bike2Drow = -1
    canvas.data.bike2Dcol = 0
    scoreOffset = 200
    canvas.create_rectangle(0, 0, canvasWidth, canvasHeight, fill="black")
    canvas.create_text(canvasWidth/2, canvasHeight-50, text = "TRON",
                       fill = "brown", font = ("Helvatica", 32, "bold"))
    canvas.create_text(canvasWidth/2-scoreOffset, canvasHeight-50,
                       text = "Player 1 score is %d " % canvas.data.player1Score,
                       fill = "dark green", font =("Helvatica", 10, "bold") )
    canvas.create_text(canvasWidth/2+scoreOffset, canvasHeight-50,
                       text = "Player 2 score is %d " % canvas.data.player2Score,
                       fill = "dark violet", font =("Helvatica", 10, "bold") )
    canvas.create_text(canvasWidth/2, canvasHeight-80,
                       text = 'Press "r" to Restart',
                       fill = "brown", font =("Helvatica", 10, "bold") )
    canvas.create_text(canvasWidth/2, canvasHeight-20,
                       text = 'Press "Enter" to Start',
                       fill = "brown", font =("Helvatica", 10, "bold") )
    canvas.create_text(canvasWidth/2-scoreOffset, canvasHeight-30,
                       text = 'Move with "up, left, down, right"',
                       fill = "dark green", font =("Helvatica", 10, "bold") )
    canvas.create_text(canvasWidth/2+scoreOffset, canvasHeight-30,
                       text = 'Move with "w,a,s,d"',
                       fill = "dark violet", font =("Helvatica", 10, "bold") )
    canvas.data.ignoreNextTimerEvent = False
    drawTronBoard()
    margin = canvas.data.margin
    cellSize = canvas.data.cellSize
    row = canvas.data.rows/2
    col = canvas.data.cols/8
    left = margin + col * cellSize
    right = left + cellSize
    top = margin + row * cellSize
    bottom = top + cellSize
    canvas.create_rectangle(left, top, right, bottom, fill="dark green")
    row = canvas.data.rows/2
    col = canvas.data.cols - canvas.data.cols/8
    left = margin + col * cellSize
    right = left + cellSize
    top = margin + row * cellSize
    bottom = top + cellSize
    canvas.create_rectangle(left, top, right, bottom, fill="dark violet")
    

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

def run(rows, cols):
    # create the root and the canvas
    global canvas
    root = Tk()
    margin = 5
    cellSize = 15
    canvasWidth = 2*margin + cols*cellSize
    canvasHeight = 2*margin + rows*cellSize+100
    canvas = Canvas(root, width=canvasWidth, height=canvasHeight)
    canvas.pack()
    # Store canvas in root and in canvas itself for callbacks
    root.canvas = canvas.canvas = canvas
    # Set up canvas data and call init
    class Struct: pass
    canvas.data = Struct()
    canvas.data.margin = margin
    canvas.data.cellSize = cellSize
    canvas.data.canvasWidth = canvasWidth
    canvas.data.canvasHeight = canvasHeight
    canvas.data.rows = rows
    canvas.data.cols = cols
    canvas.data.canvasWidth = canvasWidth
    canvas.data.canvasHeight = canvasHeight
    canvas.data.player1Score = 0
    canvas.data.player2Score = 0
    canvas.data.inGame = False
    init()
    # set up events
    root.bind("<Key>", keyPressed)
    timerFired()
    # and launch the app
    root.mainloop()  # This call BLOCKS (so your program waits until you close the window!)
    
run(40,40)


Was This Post Helpful? 0
  • +
  • -

#11 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5643
  • View blog
  • Posts: 12,359
  • Joined: 16-October 07

Re: control bug for tron bike game using Tkinter

Posted 10 August 2012 - 08:03 AM

Having two of everything immediately screams list. Also, for this, object.

I didn't want to muck up the whole thing and I doubtless introduced some problems. However, for your consideration.

import random
from Tkinter import *

class Bike(object):
	def __init__(self, player, value, hotColor, coldColor):
		self.player = player
		self.value = value
		self.hotColor, self.coldColor = hotColor, coldColor
		self.pos = (0, 0)
		self.delta = (0, 0)
		self.path = []
		
	def move(self, delta, tronBoard):
		self.delta = delta
		newPos = (self.pos[0] + self.delta[0], self.pos[1] + self.delta[1] )
		d = ( len(tronBoard), len(tronBoard[0]) )
		if (newPos[0] < 0) or (newPos[1] < 0) or (newPos[0]>=d[0]) or (newPos[1]>=d[1]) or (tronBoard[newPos[0]][newPos[1]] != 0):
			return False
		tronBoard[newPos[0]][newPos[1]] += self.value
		self.path.append(newPos)
		self.pos = newPos
		return True

	def _getRect(self, margin, cellSize, pos):
		row,col = pos
		left = margin + col*cellSize
		top = margin + row*cellSize
		return (left, top, left + cellSize, top + cellSize)
	

	def drawPath(self, margin, cellSize):
		left, top, right, bottom = self._getRect(margin, cellSize, self.path[-1])
		canvas.create_rectangle(left, top, right, bottom, fill=self.hotColor)
		if len(self.path)>=2:
			left, top, right, bottom = self._getRect(margin, cellSize, self.path[-2])
			canvas.create_rectangle(left, top, right, bottom, fill=self.coldColor)
	


def keyPressed(event):
    if event.keysym == "Return":
        canvas.data.inGame = True
    if (event.char == "q"):
        gameOver()
    elif (event.char == "r"):
        init()
    if not canvas.data.isGameOver:
        if (event.keysym == "Up"):
            moveBike(-1, 0)
        elif (event.keysym == "Down"):
            moveBike(+1, 0)
        elif (event.keysym == "Left"):
            moveBike(0,-1)
        elif (event.keysym == "Right"):
            moveBike(0,+1)
        elif (event.keysym == "a"):
            moveBike2(0,-1)
        elif (event.keysym == "s"):
            moveBike2(+1,0)
        elif (event.keysym == "w"):
            moveBike2(-1,0)
        elif (event.keysym == "d"):
            moveBike2(0, +1)


def moveBikeObj(bike, delta = None):
	if not delta:
		delta = bike.delta
	if not bike.move(delta, canvas.data.tronBoard):
		if bike.player==1:
			canvas.data.player2Score+=1
		else:
			canvas.data.player1Score+=1
		canvas.data.loser = bike.player + 1
		gameOver()
        
def moveBike(dRow, dCol):
	moveBikeObj(canvas.data.bikes[0], (dRow, dCol))
    
def moveBike2(dRow, dCol):
	moveBikeObj(canvas.data.bikes[1], (dRow, dCol))


def gameOver():
    cx = canvas.data.canvasWidth/2
    cy = canvas.data.canvasHeight/2
    if canvas.data.loser==1:
         canvas.create_text(cx, cy, text="Player 2 Wins!", fill = "brown",
                           font=("Helvetica", 32, "bold"))
    if canvas.data.loser==2:
         canvas.create_text(cx, cy, text="Player 1 Wins!", fill = "brown",
                           font=("Helvetica", 32, "bold"))
    canvas.data.isGameOver = True


def timerFired():
	if canvas.data.inGame:
		# tronBoard = canvas.data.tronBoard
		ignoreThisTimerEvent = canvas.data.ignoreNextTimerEvent
		canvas.data.ignoreNextTimerEvent = False
		if not canvas.data.isGameOver and not ignoreThisTimerEvent:
			for bike in canvas.data.bikes:
				moveBikeObj(bike)
				bike.drawPath(canvas.data.margin, canvas.data.cellSize)
	delay = 50
	canvas.after(delay, timerFired)


def drawTronBoard():
    tronBoard = canvas.data.tronBoard
    margin = canvas.data.margin
    cellSize = canvas.data.cellSize
    for row in range(len(tronBoard)):
        for col in range(len(tronBoard[0])):
			left = margin + col * cellSize
			right = left + cellSize
			top = margin + row * cellSize
			bottom = top + cellSize
			canvas.create_rectangle(left, top, right, bottom, fill="black", outline="brown")

def loadTronBoard():
    rows = canvas.data.rows
    cols = canvas.data.cols
    tronBoard = [ ]
    for row in range(rows): 
    	tronBoard += [[0] * cols]
    #player1 start position
    # tronBoard[rows/2][cols/8] = 1
    #player2 start position
    # tronBoard[rows/2][cols-cols/8] = -1
    
    canvas.data.bikes[0].pos = (rows/2, cols/8)
    canvas.data.bikes[1].pos = (rows/2, cols-cols/8)
    for bike in canvas.data.bikes:
	    tronBoard[bike.pos[0]][bike.pos[1]] = bike.value
    	
    canvas.data.tronBoard = tronBoard
    # findBike()
    # findBike2()   
    

def placeBoost():
    tronBoard = canvas.data.tronBoard
    rows = len(tronBoard)
    cols = len(tronBoard[0])
    while True:
        row = random.randint(0,rows-1)
        col = random.randint(0,cols-1)
        if (tronBoard[row][col] == 0):
            break
    tronBoard[row][col] = -1




def init():
    loadTronBoard()
    canvas.data.inDebugMode = False
    canvas.data.isGameOver = False
    # canvas.data.path1 = []
    # canvas.data.path2 = []
    canvas.data.loser = 0
    canvasWidth = canvas.data.canvasWidth
    canvasHeight = canvas.data.canvasHeight
    # canvas.data.bikeDrow = +1
    # canvas.data.bikeDcol = 0
    # canvas.data.bike2Drow = -1
    # canvas.data.bike2Dcol = 0
    canvas.data.bikes[0].delta = (1,0)
    canvas.data.bikes[1].delta = (-1,0)

    
    scoreOffset = 200
    canvas.create_rectangle(0, 0, canvasWidth, canvasHeight, fill="black")
    canvas.create_text(canvasWidth/2, canvasHeight-50, text = "TRON",
                       fill = "brown", font = ("Helvatica", 32, "bold"))
    canvas.create_text(canvasWidth/2-scoreOffset, canvasHeight-50,
                       text = "Player 1 score is %d " % canvas.data.player1Score,
                       fill = "dark green", font =("Helvatica", 10, "bold") )
    canvas.create_text(canvasWidth/2+scoreOffset, canvasHeight-50,
                       text = "Player 2 score is %d " % canvas.data.player2Score,
                       fill = "dark violet", font =("Helvatica", 10, "bold") )
    canvas.create_text(canvasWidth/2, canvasHeight-80,
                       text = 'Press "r" to Restart',
                       fill = "brown", font =("Helvatica", 10, "bold") )
    canvas.create_text(canvasWidth/2, canvasHeight-20,
                       text = 'Press "Enter" to Start',
                       fill = "brown", font =("Helvatica", 10, "bold") )
    canvas.create_text(canvasWidth/2-scoreOffset, canvasHeight-30,
                       text = 'Move with "up, left, down, right"',
                       fill = "dark green", font =("Helvatica", 10, "bold") )
    canvas.create_text(canvasWidth/2+scoreOffset, canvasHeight-30,
                       text = 'Move with "w,a,s,d"',
                       fill = "dark violet", font =("Helvatica", 10, "bold") )
    canvas.data.ignoreNextTimerEvent = False
    drawTronBoard()
    margin = canvas.data.margin
    cellSize = canvas.data.cellSize
    row = canvas.data.rows/2
    col = canvas.data.cols/8
    left = margin + col * cellSize
    right = left + cellSize
    top = margin + row * cellSize
    bottom = top + cellSize
    canvas.create_rectangle(left, top, right, bottom, fill="dark green")
    row = canvas.data.rows/2
    col = canvas.data.cols - canvas.data.cols/8
    left = margin + col * cellSize
    right = left + cellSize
    top = margin + row * cellSize
    bottom = top + cellSize
    canvas.create_rectangle(left, top, right, bottom, fill="dark violet")
    

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

def run(rows, cols):
    # create the root and the canvas
    global canvas
    root = Tk()
    margin = 5
    cellSize = 15
    canvasWidth = 2*margin + cols*cellSize
    canvasHeight = 2*margin + rows*cellSize+100
    canvas = Canvas(root, width=canvasWidth, height=canvasHeight)
    canvas.pack()
    # Store canvas in root and in canvas itself for callbacks
    root.canvas = canvas.canvas = canvas
    # Set up canvas data and call init
    class Struct: pass
    canvas.data = Struct()
    canvas.data.margin = margin
    canvas.data.cellSize = cellSize
    canvas.data.canvasWidth = canvasWidth
    canvas.data.canvasHeight = canvasHeight
    canvas.data.rows = rows
    canvas.data.cols = cols
    canvas.data.canvasWidth = canvasWidth
    canvas.data.canvasHeight = canvasHeight
    canvas.data.player1Score = 0
    canvas.data.player2Score = 0
    canvas.data.inGame = False
    canvas.data.bikes = [ Bike(1, 1,"lime green", "dark green"), Bike(2, -1, "violet", "dark violet") ]
    init()
    # set up events
    root.bind("<Key>", keyPressed)
    timerFired()
    # and launch the app
    root.mainloop()  # This call BLOCKS (so your program waits until you close the window!)
    
run(40,40)



I hate the global of everything. I'd make your data a proper class, not the ad hoc thing it is. Maybe a player class, rather than a bike class. Try to limit the scope of everything and tighten it up. Ultimately, you want to be able to handle more than two bikes...

Hope this helps.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1