ok. sorry.
heres the most recent status update:
i have 1 problems, on glich and one to do that i dont know how to do:

problem:
the text in the "info" static text is too close to the edge. how do i fix this?

glich:
when you win the game, it puts up a message box that says "play again?" and you have to click the OK button twice for it to work.

to do:
display guessed numbers in the "info" part. i'm not sure how to do this and testing has caused crashes.

thats the most recent stuff.
billy

ok. all questions in the previous post still stand (info "padding", ok double click, and guessed numbers).

but here's a new question:
i want to create a way for the player to be able to select which difficulty they want to use. the difference in difficulty would be the range for the rand int part. (ie beginner= 1-50, medium= 1-100, hard= 1-300, expert= 1-500, impossible= 1-10000)
i don't really know how to code this. should it be a class based on dialog, or should it be a function with a dialog in it? how would i "call" it if it was a class?

thanks. i'll keep working.

ok, new status report:
padding problem solved.
guessed numbers added, bug free (i think).
difficulty not solved.
ok double click glitch not solved.

here's what i did to add the guessed numbers feature:

def compare(self,event):
        """
        main code for the game. compares the player's guess to the random number generated in reset()
        """
        global number, guesses, number_guesses
        guess = self.answer.GetValue()
        try:
            guess = int(guess)
            if guess in guesses:
                self.prompts.SetValue("You have already guessed that number, try again.")
                self.answer.SetValue('')
            elif guess == number:
                self.prompts.SetValue("Yay!")
                number_guesses += 1
                self.info.SetLabel("YOU WIN!\nYou guessed " + str(number_guesses) + " time(s).")
                self.answer.SetValue('')
                wx.FutureCall(200, self.playAgain)
            elif guess > number:
                self.prompts.SetValue("Nope. Too High.")
                guesses.append(guess)
                number_guesses += 1
                self.info.SetLabel("   You have guessed " + str(number_guesses) + " time(s).\n   You have guessed the following numbers: " + str(guesses))
                self.answer.SetValue('')
            elif guess < number:
                self.prompts.SetValue("Nope. Too Low.")
                guesses.append(guess)
                number_guesses += 1
                self.info.SetLabel("   You have guessed " + str(number_guesses) + " time(s).\n   You have guessed the following numbers: " + str(guesses))
                self.answer.SetValue('')
        except TypeError:
            self.prompts.SetValue("Invalid Entry")
            self.answer.SetValue('')

there is one more thing:
when it prints out the guessed numbers, it displays brackets around them ([]).
is there a way to remove a specific character from a string?

nothing solved as of yet, but i have a new problem:
the try... except part doesn't work. it just says that there's an error in the function and nothing else happens.

now i have used .strip('[]') to take off the brackets around the guesses part.

try... except still doesn't work.
difficulty not even attempted.
yes double click not solved.

lol. i didn't realize til today that the tutorials i've been watching are paulthom's tutorials. thanks!

Oh God, those things. They are so embarrassing, not the content so much as my voice, they were all done just before my voice broke. So i am a puny little kid it sounds :$

its not that bad, and they really helped.

def playAgain(self):
        msgbox = wx.MessageDialog(self,message="Play Again?",style = wx.ICON_QUESTION|wx.OK|wx.CANCEL)
        if msgbox.ShowModal() == wx.ID_CANCEL:
            self.Destroy()
        elif msgbox.ShowModal() == wx.ID_OK:
            msgbox.Destroy()
            self.reset()

Okay the double click is because Python needs to call msgbox.ShowModal() twice here. Once to check the if, then again to check the elif (granted that the if is false). Here's a better way to write it:

def playAgain(self):
        msgbox = wx.MessageDialog(self,message="Play Again?",style = wx.ICON_QUESTION|wx.OK|wx.CANCEL)
        usr_ans = msgbox.ShowModal()
        if usr_ans == wx.ID_CANCEL:
            self.Destroy()
        elif usr_ans == wx.ID_OK:
            msgbox.Destroy()
            self.reset()

Does that explanation make sense? HTH

it just says that there's an error in the function and nothing else happens.

Can you explain this a little emore? Are you getting an error message? Any traceback you could post?

i cant post it right now, because im at school, but i will later.

now that i think about it, instead of elif , i could just use else , couldn't i?

status update:

old (not solved) problems:
1) try... except: when i type in a non-integer answer, it gives me this:

Traceback (most recent call last):
  File "guesswithwx.py", line 51, in compare
    guess = int(guess)
ValueError: invalid literal for int() with base 10: 'g'

any ideas as to what's not working?


2) No idea on how to attempt a difficulty feature. the difficulty feature would put up a dialog or something that would allow the player to choose how difficult the game is (and maybe even allow a custom difficulty feature?). It would take the place of the reset() function in the most recent posting of my script.

solved problems:
1) the "double click" part of the play again dialog was fixed by using else instead of elif.

new problems:
none (yay! :))


thats the most recent update!
billy

status update (5:00pm central on friday):

>>> not solved problems:
1) difficulty feature still not implemented.

>>> solved problems:
1) try... except feature works. changed TypeError to ValueError .

>>> new problems:
none.

thats it!
billy

i cant post it right now, because im at school, but i will later.

now that i think about it, instead of elif , i could just use else , couldn't i?

Yup that would also work. Using elif makes Python still evaluate the statement following it. Whereas else is just a catch-all alternative

The difficulty part is "difficult" to answer as there's many ways to do it. As far as the user selecting the difficulty, you could custom roll your own message window that had multiple buttons on it (one for each difficulty) that would pop up during the call to reset() alternately you could simply pop up a textInput field that would have the user type in the difficulty setting, or perhaps a drop-down menu on the main window or some radio buttons to choose the difficulty....

I guess how you want to do it depends on your preffered style. What's your latest code look like? I'd like to try it out and see how it feels...

well, i was picturing a popup that had a drop down menu or some radio buttons. i never thought of putting it in the existing reset() function.
here's the code:

import wx, random
class MainWindow(wx.Frame):
    """creates the main window."""
    def __init__(self):
        """Creates the parts of the program, organizes them, and gets the ball rolling"""
        wx.Frame.__init__(self,None,title="Guessing Game",size = (500,200))
        self.SetBackgroundColour("gray")

        #PARTS
        self.displayprompt = wx.BoxSizer(wx.VERTICAL)
        self.answer = wx.TextCtrl(self,style=wx.PROCESS_ENTER)
        self.prompts = wx.TextCtrl(self,style = wx.TE_READONLY)
        self.info = wx.StaticText(self)

        #ORGANIZING
        self.displayprompt.Add(self.info,proportion=1,flag= wx.EXPAND)
        self.displayprompt.Add(self.prompts,proportion=0,flag= wx.EXPAND, border=0)
        self.displayprompt.Add(self.answer,proportion=0,flag = wx.EXPAND, border=0)

        #BINDING
        self.answer.Bind(wx.EVT_TEXT_ENTER,self.compare)

        #SHOWING AND CALLING
        self.SetSizer(self.displayprompt)
        self.Move((200, 200))
        self.Show(True)
        self.reset()

    #FUNCTIONS
    def reset(self):
        """creates the reset function, which sets all variables to default at the beginning of the game"""
        global number, guesses, number_guesses, infoguess, infonumber, infoother
        number = random.randint(1,100)
        guesses = ["None"]
        number_guesses = 0
        infoguess = "\n     You have guessed: " +str(guesses).strip('[\'\']')
        infonumber = "\n     You have guessed " +str(number_guesses)+ " time(s)."
        infoother = "\n     Let's get started!"
        self.prompts.SetValue("Guess the number I'm thinking of!")
        self.info.SetLabel(infoother+infoguess+infonumber)

    def compare(self,event):
        """main code for the game. compares the player's guess to the random number generated in reset()"""
        global number, guesses, number_guesses, infoguess, infonumber, infoother
        try:
            guess = int(self.answer.GetValue())
            if guess in guesses:
                self.prompts.SetValue("You have already guessed that number, try again.")
                self.answer.SetValue('')
            elif guess == number:
                number_guesses += 1
                infoguess = "\n     You have guessed: " +str(guesses).strip('[\'None\'\,]')
                infoother = "\n     You guessed it!"
                if number_guesses == 1:
                    infonumber = "\n     You have guessed " +str(number_guesses)+ " time."
                else:
                    infonumber = "\n     You have guessed " +str(number_guesses)+ " times."
                self.info.SetLabel(infoother+infoguess+infonumber)
                self.prompts.SetValue("Yay!")
                self.answer.SetValue('')
                wx.FutureCall(200, self.playAgain)
            elif guess > number:
                guesses.append(guess)
                number_guesses += 1
                infoguess = "\n     You have guessed: " +str(guesses).strip('[\'None\'\,]')
                infoother = "\n     Guessing Game"
                if number_guesses == 1:
                    infonumber = "\n     You have guessed " +str(number_guesses)+ " time."
                else:
                    infonumber = "\n     You have guessed " +str(number_guesses)+ " times."
                self.info.SetLabel(infoother+infoguess+infonumber)
                self.prompts.SetValue("Nope. Too High.")
                self.answer.SetValue('')
            elif guess < number:
                guesses.append(guess)
                number_guesses += 1
                infoguess = "\n     You have guessed: " +str(guesses).strip('[\'None\'\,]')
                infoother = "\n     Guessing Game"
                if number_guesses == 1:
                    infonumber = "\n     You have guessed " +str(number_guesses)+ " time."
                else:
                    infonumber = "\n     You have guessed " +str(number_guesses)+ " times."
                self.info.SetLabel(infoother+infoguess+infonumber)
                self.prompts.SetValue("Nope. Too Low.")
                self.answer.SetValue('')
        except ValueError:
            self.prompts.SetValue("Invalid Entry")
            self.answer.SetValue('')

    def playAgain(self):
        """this function asks the player if they want to play again."""
        msgbox = wx.MessageDialog(self,message="You guessed it! It was "+str(number)+".\nPlay Again?",caption="Play Again?",style = wx.ICON_QUESTION|wx.YES_NO)
        if msgbox.ShowModal() == wx.ID_NO:
            self.Destroy()
        else:
            self.reset()
            msgbox.Destroy()

app = wx.App(redirect=False)
frame = MainWindow()
app.MainLoop()

oh! I just remembered a feature i would like to add: high score saving.
how would i:
1) save the top five scores to a text file (xml?).
2) call them back to display them in the game.
3) add a feature after playAgain() to let them enter their name.
4) make the text file have sections for each difficulty, and recall the data for the difficulty that the player selects only.

probably pretty complicated, but thanks for any tips.
(NOTE: its pretty obvious, but in order to have #4, i would have to have the difficulties up and running.)

ok, im starting to work on the difficulty feature.
here's the code to make it display, but i have no idea how to make it do something when you click on ok and choose one.

class Diff(wx.Dialog):
     def __init__(self, parent, id, title):
        wx.Dialog.__init__(self, parent, id, title, size=(255, 230))

        panel = wx.Panel(self, -1)
        diovbox = wx.BoxSizer(wx.VERTICAL)

        wx.StaticBox(panel, -1, 'Difficulty', (5, 5), (240, 150))
        wx.RadioButton(panel, 10, 'Easy (1-100)', (15, 30), style=wx.RB_GROUP)
        wx.RadioButton(panel, 11, 'Medium (1-500)', (15, 55))
        wx.RadioButton(panel, 12, 'Hard (1-1000)', (15, 80))
        wx.RadioButton(panel, 13, 'Impossible (1-10000, Good Luck!)', (15, 105))
        okButton = wx.Button(self, 14, 'Ok', size=(70, 30))

        diovbox.Add(panel)
        diovbox.Add(okButton, 1, wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM, 10)

        self.SetSizer(diovbox)

and then in the reset function i have this code:

dio = Diff(self,-1,title="Difficulty")
        dio.ShowModal()
        dio.Destroy()

how do i detect which one is chosen. that is the question.
yeah.

ok, status update (12:50 on sat, may 23):

>>> not solved problems:
1) high score feature. it would record the player's score according to difficulty and if it was in the top five scores, then if it is, write it in a file. in game, it would load the high scores for the chosen difficulty and display them.

>>> solved problems:
1) I figured out how to fix the previous problem (detect which is chosen), but it led to the problem above.

>>> new problems:
1) bind not working. code:

class Diff(wx.Dialog):
    def __init__(self, parent, id, title):
        wx.Dialog.__init__(self, parent, id, title, size=(255, 185))
        diovbox = wx.BoxSizer(wx.VERTICAL)

        wx.StaticBox(self, -1, 'Difficulty', (5, 5), (240, 150))
        self.easy = wx.Button(self, easy_id, 'Easy (1-100)', pos=(15, 40))
        self.easy.Bind(wx.EVT_BUTTON,self.ok(f=1,s=1))
        self.med = wx.Button(self, med_id, 'Medium (1-500)', pos=(15, 65))
        self.med.Bind(wx.EVT_BUTTON,self.ok(f=2,s=2))
        self.hard = wx.Button(self, hard_id, 'Hard (1-1000)', pos=(15, 90))
        self.hard.Bind(wx.EVT_BUTTON,self.ok(f=3,s=3))
        self.imp = wx.Button(self, impossible_id, 'Impossible (1-10000, Good Luck!)', pos=(15, 115))
        self.imp.Bind(wx.EVT_BUTTON,self.ok(f=4,s=4))

        diovbox.Add(self.easy)
        diovbox.Add(self.med)
        diovbox.Add(self.hard)
        diovbox.Add(self.imp)
        self.ShowModal()
        self.SetSizer(diovbox)

    def ok(self,event,f=1,s=1):
        global number
        number = random.randint(f,s)
        self.Destroy()

displays this error:

File "guesswithwx.py", line 118, in __init__
    self.easy.Bind(wx.EVT_BUTTON,self.ok(f=1,s=1))
TypeError: ok() takes at least 2 non-keyword arguments (1 given)

what do i do?


thanks for all the help so far!
billy

status update (1:30 on sat may 23):

>>> not solved problems:
1) High scores not started. the high score feature would save and read the top high scores for the chosen difficulty and display them in game.
See previous posts for a more in depth explanation.

>>> solved problems:
1) difficulty implemented! i did it in sort of a roundabout, not conventional sort of way though. right now it uses buttons, each one with it's own function, to set the range for the number to be guessed. tips are highly appreciated! i would prefer it to use radio button thingies, but i don't know how to do that. heres the code as of now:

import wx, random

easy_id = 101
med_id = 102
hard_id = 103
impossible_id = 104
ok_id = 105


class MainWindow(wx.Frame):
    """creates the main window."""
    def __init__(self):
        """Creates the parts of the program, organizes them, and gets the ball rolling"""
        wx.Frame.__init__(self,None,title="Guessing Game",size = (500,200))
        self.SetBackgroundColour("gray")

        #PARTS
        self.displayprompt = wx.BoxSizer(wx.VERTICAL)
        self.answer = wx.TextCtrl(self,style=wx.PROCESS_ENTER)
        self.prompts = wx.TextCtrl(self,style = wx.TE_READONLY)
        self.info = wx.StaticText(self)

        #ORGANIZING
        self.displayprompt.Add(self.info,proportion=1,flag= wx.EXPAND)
        self.displayprompt.Add(self.prompts,proportion=0,flag= wx.EXPAND, border=0)
        self.displayprompt.Add(self.answer,proportion=0,flag = wx.EXPAND, border=0)

        #BINDING
        self.answer.Bind(wx.EVT_TEXT_ENTER,self.compare)

        #SHOWING AND CALLING
        self.SetSizer(self.displayprompt)
        self.Move((200, 200))
        self.Show(True)
        self.reset()

    #FUNCTIONS
    def reset(self):
        """creates the reset function, which sets all variables to default at the beginning of the game"""
        global number, guesses, number_guesses
        number = random.randint(1,100)
        dio = Diff(self,-1,title="Difficulty")
        guesses = ["None"]
        number_guesses = 0
        infoguess = "\n     You have guessed: " +str(guesses).strip('[\'\']')
        infonumber = "\n     You have guessed " +str(number_guesses)+ " time(s)."
        infoother = "\n     Let's get started!"
        self.prompts.SetValue("Guess the number I'm thinking of!")
        self.info.SetLabel(infoother+infoguess+infonumber)

    def compare(self,event):
        """main code for the game. compares the player's guess to the random number generated in reset()"""
        global number, guesses, number_guesses
        try:
            guess = int(self.answer.GetValue())
            if guess in guesses:
                self.prompts.SetValue("You have already guessed that number, try again.")
                self.answer.SetValue('')
            elif guess == number:
                number_guesses += 1
                guesses.append(guess)
                infoguess = "\n     You have guessed: " +str(guesses).strip('[\'None\'\,]')
                infoother = "\n     You guessed it!"
                if number_guesses == 1:
                    infonumber = "\n     You have guessed " +str(number_guesses)+ " time."
                else:
                    infonumber = "\n     You have guessed " +str(number_guesses)+ " times."
                self.info.SetLabel(infoother+infoguess+infonumber)
                self.prompts.SetValue("Yay!")
                self.answer.SetValue('')
                wx.FutureCall(200, self.playAgain)
            elif guess > number:
                guesses.append(guess)
                number_guesses += 1
                infoguess = "\n     You have guessed: " +str(guesses).strip('[\'None\'\,]')
                infoother = "\n     Guessing Game"
                if number_guesses == 1:
                    infonumber = "\n     You have guessed " +str(number_guesses)+ " time."
                else:
                    infonumber = "\n     You have guessed " +str(number_guesses)+ " times."
                self.info.SetLabel(infoother+infoguess+infonumber)
                self.prompts.SetValue("Nope. Too High.")
                self.answer.SetValue('')
            elif guess < number:
                guesses.append(guess)
                number_guesses += 1
                infoguess = "\n     You have guessed: " +str(guesses).strip('[\'None\'\,]')
                infoother = "\n     Guessing Game"
                if number_guesses == 1:
                    infonumber = "\n     You have guessed " +str(number_guesses)+ " time."
                else:
                    infonumber = "\n     You have guessed " +str(number_guesses)+ " times."
                self.info.SetLabel(infoother+infoguess+infonumber)
                self.prompts.SetValue("Nope. Too Low.")
                self.answer.SetValue('')
        except ValueError:
            self.prompts.SetValue("Invalid Entry")
            self.answer.SetValue('')

    def playAgain(self):
        """this function asks the player if they want to play again."""
        msgbox = wx.MessageDialog(self,message="You guessed it! It was "+str(number)+".\nPlay Again?",caption="Play Again?",style = wx.ICON_QUESTION|wx.YES_NO)
        if msgbox.ShowModal() == wx.ID_NO:
            self.Destroy()
        else:
            self.reset()
            msgbox.Destroy()

class Diff(wx.Dialog):
    def __init__(self, parent, id, title):
        wx.Dialog.__init__(self, parent, id, title, size=(255, 185))
        diovbox = wx.BoxSizer(wx.VERTICAL)

        wx.StaticBox(self, -1, 'Difficulty', (5, 5), (240, 150))
        self.easy = wx.Button(self, easy_id, 'Easy (1-100)', pos=(15, 40))
        self.easy.Bind(wx.EVT_BUTTON,self.easyFunc)
        self.med = wx.Button(self, med_id, 'Medium (1-500)', pos=(15, 65))
        self.med.Bind(wx.EVT_BUTTON,self.medFunc)
        self.hard = wx.Button(self, hard_id, 'Hard (1-1000)', pos=(15, 90))
        self.hard.Bind(wx.EVT_BUTTON,self.hardFunc)
        self.imp = wx.Button(self, impossible_id, 'Impossible (1-10000, Good Luck!)', pos=(15, 115))
        self.imp.Bind(wx.EVT_BUTTON,self.impFunc)

        diovbox.Add(self.easy)
        diovbox.Add(self.med)
        diovbox.Add(self.hard)
        diovbox.Add(self.imp)
        self.ShowModal()
        self.SetSizer(diovbox)
        self.Destroy
    def easyFunc(self,event):
        global number
        number = random.randint(1,100)
        self.Destroy()
    def medFunc(self,event):
        global number
        number = random.randint(1,500)
        self.Destroy()
    def hardFunc(self,event):
        global number
        number = random.randint(1,1000)
        self.Destroy()
    def impFunc(self,event):
        global number
        number = random.randint(1,10000)
        self.Destroy()
app = wx.App(redirect=False)
frame = MainWindow()
app.MainLoop()

>>> new problems:
none

thanks for any tips on how to improve the difficulty feature.

yeah, i have too. its a nice reference.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.