Skip to main content
gamedev.net
🔒 Locked

Python Game

Started by Leonius Oct 6, 2010 at 2:34 PM 9 replies 4.1k views
Original Post
Leonius
Leonius
Recently, my CS professor gave our class an assignment where we had to program a game like the one at http://cs.gettysburg.edu/projects/pig/piggame.html. It wouldn't be a problem if he had actually taught us how to do it. I have almost no experience with programming( just some experience with modding Morrowind ). So far, my code looks like this:

import randomfrom Tkinter import *import tkMessageBoxitems = [1,2,3,4,5,6]Roll = random.choice(items)#Initialized value to zero, which is used in the dieRoll functionvalue = 0Winner = 5 #Temporary value untill I can get the program working#This tells the program whos turn it is. When true, Player 1's turn. When false, Player 2's turnPlayerTurn = Trueclass GUIFramework(Frame):           def __init__( self, master = None ):                      """Initialise the base class"""        Frame.__init__( self, master )                """Set the Window Title"""        self.master.title("Pig Game")                """Display the main window"""        self.grid( padx = 200, pady = 100 )        self.CreateWidgets()           def CreateWidgets(self):                                """Create the Turn Total text"""        self.TurnTotal = Label( self, text = "Turn Total" )        self.TurnTotal.grid( row = 0, column = 0 )        self.PlayerOne = Label( self, text = "Player 1" )        self.PlayerOne.grid( row = 0, column = 12 )        self.PlayerTwo = Label( self, text = "Player 2" )        self.PlayerTwo.grid( row = 0, column = 24 )        self.Winner = Label( self, text = "Winner" )        self.Winner.grid( row = 0, column = 36 )                #Takes the value aquired from dieRoll and places it on the screen underneath "Turn Total"        self.TurnTotalValue = Label( self, text = value )        self.TurnTotalValue.grid( row = 4, column = 0 )        #Takes the returned value from checkWinner and places it on the screen underneath "Winner"        self.WinnerValue = Label( self, text = Winner )        self.WinnerValue.grid( row = 4, column = 36 )        self.PlayerOneScore = Label( self, text = "Place Holder" ) #Updated with Player1Score        self.PlayerOneScore.grid( row = 4, column = 12 )        self.PlayerTwoScore = Label( self, text = "Place Holder" ) #Updated with Player2Score        self.PlayerTwoScore.grid( row = 4, column = 24 )        #This creates the button which is used by the dieRoll function to generate a random number between 1 and 6        self.btnRoll = Button( self, text = "Roll", command = self.dieRoll )        self.btnRoll.grid( row = 8, column = 0 )                #This creates the button that, when pressed, calls the function updateScore        #and puts the value in self.TurnTotalValue to either PlayerOneScore or PlayerTwoScore, depending on whose turn it is        self.btnHold = Button( self, text = "Hold", command = self.scoreUpdate )        self.btnHold.grid( row = 8, column = 12 )#This is the function that is called when btnRoll is pressed. This function generates a random number between 1 and 6. If a 1 is rolled, the value in TurnTotalValue#is set to 0 and the turn is switched. If a 2-6 is rolled, the value in TurnTotalValue is updated by adding the new value generated by the dieRoll to the previous#value in TurnTotalValue    def dieRoll(self) :        value = 0        Roll = random.choice( items )        if Roll == 1 :            value = 0            PlayerTurn = False            print "You Lose"        else :                value = value + Roll            print Roll            TurnTotal = value            self.value = ( value )        return ( value )    #This function is called when btnHold is pressed.     def scoreUpdate( value ) :        if PlayerTurn == True :            Player1Score = value            value = 0            PlayerTurn = False            checkWinner        else :            Player1Score = value            value = 0            PlayerTurn = True            checkWinner    #This function is called in the updateScore function    def checkWinner() :        if Player1Score >= 100 :            Winner = "Player 1"        else :            Winner = "Player 2"        return ( Winner )                if __name__ == "__main__":    guiFrame = GUIFramework()    guiFrame.mainloop()"""#Function for the computer's turn. Will be added at later time.def computerTurn() :    while (value < 20) :        Roll = random.choice(items)        if Roll == 1 :            print "You Lose"            value = 0            Player1Turn = True            break        else :            value = value + Roll            print Roll                TurnTotal = value        print TurnTotal                return ( TurnTotal )"""        """#Function for starting a new gamedef newGame() :    Player1Turn = True    TurnTotal = 0    YourScore = 0    ComputerScore = 0    #NewGame.Button = Disabled    #Winner.Field = Disabled"""


I would have attached the file, but I couldn't where to do it. Like I said, I have no experience coding in high-level programming languages, so I have no idea whats wrong with my code

[Edited by - Leonius on October 6, 2010 4:47:57 PM]
AndyEsser
AndyEsser
Post your code between [ source ][ /source ] tags (remove spaces).

Also, what isn't working? You haven't actually said what your problems are.
Leonius
Leonius
Sorry, I thought I had said what they were. Anyway, the problems that I'm having right now are:

When the Roll button is pressed, it calls to dieRoll correctly, but never adds the value generated by dieRoll to the value in TurnTotalValue

The Hold button doesn't work. Whenever I click on it I get an error saying "UnboundLocalError: local variable 'PlayerTurn' referenced before assignment"

I think that the way I have the program deciding whose turn it is is wrong as well


Other than that, until I get the problems mentioned above working, I am unsure as to what else might be the problem
nossrannug
nossrannug
Might want to use self.value and self.PlayerScore and so on.
Dont think you want dieRoll to return anything. You just want it to add the roll to self.value until the Hold button is pressed or until you roll a 1.

A great tkinter guide: http://effbot.org/tkinterbook/
After learning Python for 1 week I was able to make Reversi with AI using only this guide.

Also might want to use textvariable for the player score labels instead of text.
Leonius
Leonius
So, I did what you suggested, but it still didn't work. I'm not sure if I did something wrong, but something's not working
Leonius
Leonius
Never mind, I got it working. Thanks nossrannug for the help
Leonius
Leonius
So, I had gotten a variation of the program that I posted on here a few days ago to work( my teacher wanted us to do something different with it ). Now he wants us to change the program so that you play against a computer. I have gotten most of the code working, but I'm having a problem with a few parts of it.

import randomfrom Tkinter import *import tkMessageBoximport timeclass Game(Frame):           def __init__( self, master = None ):        self.PlayerTurn = 0 #0 for player 1 turn, 1 for player 2 turn        self.Roll = 0        self.items = [1,2,3,4,5,6]        self.computerrolls = [1,2,3,4,5,6]                      """Initialise the base class"""        Frame.__init__( self, master )                """Set the Window Title"""        self.master.title("Pig Game")                """Display the main window"""        self.grid( padx = 200, pady = 100 )                                """Create the Turn Total text"""        self.TurnTotal = Label( self, text = "Turn Total" )        self.TurnTotal.grid( row = 0, column = 0 )        self.value = StringVar()        self.value.set( '0' )        self.TurnTotalValue = Label( self, textvariable = self.value )        self.TurnTotalValue.grid( row = 4, column = 0 )        self.PlayerOne = Label( self, text = "Player 1", bg = 'green' )        self.PlayerOne.grid( row = 0, column = 12 )        self.Player1 = StringVar()        self.Player1.set( '0' )        self.PlayerOneScore = Label( self, text = '0', textvariable = self.Player1 )        self.PlayerOneScore.grid( row = 4, column = 12 )        self.Computer = Label( self, text = "Computer" )        self.Computer.grid( row = 0, column = 24 )        self.ComputerT = StringVar()        self.ComputerT.set( '0' )        self.ComputerScore = Label( self, text = '0', textvariable = self.ComputerT )        self.ComputerScore.grid( row = 4, column = 24 )        """self.Winner = Label( self, text = "Winner" )        self.Winner.grid( row = 0, column = 36 )        self.WinnerValue = StringVar()        self.WinnerValue.set( ' ' )         self.WinnerValueField = Label( self, text = ' ', textvariable = self.WinnerValue )        self.WinnerValueField.grid( row = 4, column = 36 )"""               #This creates the button which is used by the dieRoll function to generate a random number between 1 and 6        self.btnRoll = Button( self, text = "Roll", command = self.dieRoll )        self.btnRoll.grid( row = 8, column = 0 )                #This creates the button that, when pressed, calls the function updateScore        #and puts the value in self.TurnTotalValue to either PlayerOneScore or PlayerTwoScore, depending on whose turn it is        self.btnHold = Button( self, text = "Hold", command = self.scoreUpdate )        self.btnHold.grid( row = 8, column = 12 )    #This is the function that is called when btnRoll is pressed. This function generates a random number between 1 and 6. If a 1 is rolled, the value in TurnTotalValue    #is set to 0 and the turn is switched. If a 2-6 is rolled, the value in TurnTotalValue is updated by adding the new value generated by the dieRoll to the previous    #value in TurnTotalValue    def dieRoll( self ) :        self.Roll = random.choice( self.items )        if self.Roll == 1 :            self.value.set( '0' )            self.turn()            self.computerTurn()        else :                self.value.set( int( self.value.get() ) + self.Roll )    def computerTurn( self ) :        for i in range ( random.choice( self.computerrolls ) ) :            self.Roll = random.choice( self.items )            if self.Roll == 1 :                #self.PlayerTurn = 0                self.value.set( '0' )                self.turn()                break            else :                self.value.set( int( self.value.get() ) + self.Roll )        self.scoreUpdate()                #This function is called when btnHold is pressed.     def scoreUpdate( self ) :                if self.PlayerTurn == 0 :            self.Player1.set( int( self.value.get() ) + int( self.Player1.get() ) )            self.value.set( '0' )                        self.turn()        else :            self.ComputerT.set( int( self.value.get() ) + int( self.ComputerT.get() ) )            self.value.set( '0' )            self.turn()            #self.checkWinner()    def turn( self ) :        if self.PlayerTurn == 0 :            self.PlayerTurn = 1            self.PlayerOne = Label( self, text = "Player 1" )            self.PlayerOne.grid( row = 0, column = 12 )            self.PlayerTwo = Label( self, text = "Computer", bg = 'green' )            self.PlayerTwo.grid( row = 0, column = 24 )        else :            self.PlayerTurn = 0            self.PlayerTwo = Label( self, text = "Computer" )            self.PlayerTwo.grid( row = 0, column = 24 )            self.PlayerOne = Label( self, text = "Player 1", bg = 'green' )            self.PlayerOne.grid( row = 0, column = 12 )                          if __name__ == "__main__":    guiFrame = Game()    guiFrame.mainloop()



The problems I'm having now are getting the computer to play when you roll a one or press the Hold button, updating the score generated by the computer to the screen, and getting the turns to change. I've tried pretty much everything I can think of, but most of the time I get a "RuntimeError: maximum recursion depth exceeded while calling a Python object" error.
nossrannug
nossrannug
    def computerTurn( self ) :        for i in range ( random.choice( self.computerrolls ) ) :            self.Roll = random.choice( self.items )            if self.Roll == 1 :                #self.PlayerTurn = 0                self.value.set( '0' )                #self.turn()   <-- Don't need this. It gets called in scoreUpdate                break            else :                self.value.set( int( self.value.get() ) + self.Roll )        self.scoreUpdate()


You don't need to call self.turn() in the for loop since it gets called in self.scoreUpdate().
And you want the computer to make its move when the player presses the Hold button. So you would have to add in scoreUpdate() if the player pressed the hold button call self.computerTurn().
Leonius
Leonius
So, I did what you suggested, but now every time I press the Hold button I get a "RuntimeError: maximum recursion depth exceeded while calling a Python object" error.
nossrannug
nossrannug
import randomfrom tkinter import *class Game(Frame):           def __init__( self, master = None ):        self.PlayerTurn = 0 #0 for player 1 turn, 1 for player 2 turn        self.Roll = 0        self.items = [1,2,3,4,5,6]        self.computerrolls = [1,2,3,4,5,6]                      """Initialise the base class"""        Frame.__init__( self, master )                """Set the Window Title"""        self.master.title("Pig Game")                """Display the main window"""        self.grid( padx = 200, pady = 100 )                                """Create the Turn Total text"""        self.TurnTotal = Label( self, text = "Turn Total" )        self.TurnTotal.grid( row = 0, column = 0 )        self.value = StringVar()        self.value.set( '0' )        self.TurnTotalValue = Label( self, textvariable = self.value )        self.TurnTotalValue.grid( row = 4, column = 0 )        self.PlayerOne = Label( self, text = "Player 1", bg = 'green' )        self.PlayerOne.grid( row = 0, column = 12 )        self.Player1 = StringVar()        self.Player1.set( '0' )        self.PlayerOneScore = Label( self, text = '0', textvariable = self.Player1 )        self.PlayerOneScore.grid( row = 4, column = 12 )        self.Computer = Label( self, text = "Computer" )        self.Computer.grid( row = 0, column = 24 )        self.ComputerT = StringVar()        self.ComputerT.set( '0' )        self.ComputerScore = Label( self, text = '0', textvariable = self.ComputerT )        self.ComputerScore.grid( row = 4, column = 24 )        """self.Winner = Label( self, text = "Winner" )        self.Winner.grid( row = 0, column = 36 )        self.WinnerValue = StringVar()        self.WinnerValue.set( ' ' )         self.WinnerValueField = Label( self, text = ' ', textvariable = self.WinnerValue )        self.WinnerValueField.grid( row = 4, column = 36 )"""               #This creates the button which is used by the dieRoll function to generate a random number between 1 and 6        self.btnRoll = Button( self, text = "Roll", command = self.dieRoll )        self.btnRoll.grid( row = 8, column = 0 )                #This creates the button that, when pressed, calls the function updateScore        #and puts the value in self.TurnTotalValue to either PlayerOneScore or PlayerTwoScore, depending on whose turn it is        self.btnHold = Button( self, text = "Hold", command = self.scoreUpdate )        self.btnHold.grid( row = 8, column = 12 )    #This is the function that is called when btnRoll is pressed. This function generates a random number between 1 and 6.    #If a 1 is rolled, the value in TurnTotalValue    #is set to 0 and the turn is switched. If a 2-6 is rolled, the value in TurnTotalValue    #is updated by adding the new value generated by the dieRoll to the previous    #value in TurnTotalValue    def dieRoll( self ) :        self.Roll = random.choice( self.items )        if self.Roll == 1 :            self.value.set( '0' )            self.turn()            self.computerTurn()        else :                self.value.set( int( self.value.get() ) + self.Roll )    def computerTurn( self ) :        for i in range ( random.choice( self.computerrolls ) ) :            self.Roll = random.choice( self.items )            if self.Roll == 1 :                #self.PlayerTurn = 0                self.value.set( '0' )                break            else :                self.value.set( int( self.value.get() ) + self.Roll )        self.scoreUpdate()                #This function is called when btnHold is pressed.     def scoreUpdate( self ) :                if self.PlayerTurn == 0 :            self.Player1.set( int( self.value.get() ) + int( self.Player1.get() ) )            self.value.set( '0' )                        self.turn()            self.computerTurn()        else :            self.ComputerT.set( int( self.value.get() ) + int( self.ComputerT.get() ) )            self.value.set( '0' )            self.turn()            #self.checkWinner()    def turn( self ) :        if self.PlayerTurn == 0 :            self.PlayerTurn = 1            self.PlayerOne = Label( self, text = "Player 1" )            self.PlayerOne.grid( row = 0, column = 12 )            self.PlayerTwo = Label( self, text = "Computer", bg = 'green' )            self.PlayerTwo.grid( row = 0, column = 24 )        else :            self.PlayerTurn = 0            self.PlayerTwo = Label( self, text = "Computer" )            self.PlayerTwo.grid( row = 0, column = 24 )            self.PlayerOne = Label( self, text = "Player 1", bg = 'green' )            self.PlayerOne.grid( row = 0, column = 12 )                          if __name__ == "__main__":    guiFrame = Game()    guiFrame.mainloop()

Try copy paste this code. It works for me. I'm using python3.1.2, should work for 2.# if you only change tkinter to Tkinter.
Leonius
Leonius
It works now. Thank you nossrannug

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.