Posted on 4 Comments

Jumbled Words game in Python

I talked about a jumbled words, GUI-based, game in my last post. I made that game just for fun. It was not at all hard to make when you are using a write-less-do-more-language, like Python.

I would like to share the code of that program with you and give a short tutorial on how to create your own Jumbled Words game. The tutorial is platform-independent. So, no matter if you are using Windows or Linux or Mac, the tut will work out in all the cases.

Here’s a screenshot of the Jumbled Words game running in Linux.

  • First of all, you will need the Python programming language installed on your system. Get it from here: http://python.org/download/.
  • Next, you’ll need a GUI-tool kit for Python which would actually allow you create GUI based applications. I used the wxPython tool kit. Get it from here: http://wxpython.org/download.php#binaries.
  • After installing Python and wxPython on your system, you’ll be ready to start writing the code now.
  • Create a new file, copy-paste the following contents in it, and save it by the name JumbledGUI.py.
  • # Author: Anurag Bhandari | Contact: anurag.bhd@gmail.com
    #
    # Program: Jumbled Words Game | Version: 1.0 | Licence: GPLv2
    #
    # This is the console version of the  jumbled words solving game
    # It's sure an interesting thing to do in free time
     
    import wx
     
    # First, we define a dictionary of jumbled words
    dict = {"special":"licapes", "verify":"rfvyie", "guava":"augav", "begin":"ngibe",
            "compression":"serniospmoc", "praying":"igyaprn", "linux":"uilxn",
            "opposite":"seopopit", "depricated": "cpdirdaete",
            "leonardo da vinci":"o draconian devil", "the mona lisa":"oh lame saint",
            "dreaming":"earimngd", "tormented":"nemortted", "flabbergasted": "tasedbgaberlaf",
            "meticuluos":"ecusoulmit", "rectify":"fitecry", "mobile":"ibelmo",
            "computer":"mertopcu", "granular":"lrgaruna", "metro":"torem",
            "outrageous":"gretsouauo", "nothing":"hotning", "appreciable":"celbepiapra", "vandalism":"misdanlav", "tropical":"ptorlica"}
     
    def func():
        'This is the core function of the program'
        # The result of popitem() method is a tuple
        # The following is an example of "sequence unpacking"
        word, jumbled = dict.popitem()
        return word, jumbled
     
    def guess(event):
        ans = input_word.GetValue()
        if(ans == query[0]):
            result.SetLabel(label="Congrats! You got it right.")
        else:
            result.SetLabel(label="Sorry, wrong answer. Better luck next time!")
     
    def next(event):
        # After a person clicks the Start button for the first time, this will happen
        nextButton.SetLabel("Next")
        guessButton.Enable()
        hintButton.Enable()
        input_word.SetValue("")
        # Unless we define the variable "query" as global, the function "guess" won't be able to access it
        global query
        query = func()
        if(dict!={}):
            question.SetLabel(label="The jumbled word is: "+query[1])
            result.SetLabel(label="Waiting for your input...")
        else:
            question.SetLabel(label="Game Over!")
            result.SetLabel(label="Yup, the game is finally over!")
            guessButton.Disable()
            nextButton.Disable()
            hintButton.Disable()
     
    def hint(event):
        input_word.SetValue(query[0])
     
    app = wx.App()
    # The definition of splash screen is done after an object for the wx.App class has been defined. Same applies to all the other widgets
    splash_image = wx.Image("splash.bmp", wx.BITMAP_TYPE_BMP)
    bmp = splash_image.ConvertToBitmap()
    wx.SplashScreen(bmp, wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT, 2000, None, -1)
    wx.Yield()
    win = wx.Frame(None, title="Jumbled Words Game", size=(460, 345))
    win.SetIcon(wx.Icon('star.ico', wx.BITMAP_TYPE_ICO))
    win.CenterOnScreen()
    bkg = wx.Panel(win)
    guessButton = wx.Button(bkg, label='Guess')
    guessButton.Bind(wx.EVT_BUTTON, guess)
    guessButton.SetDefault()
    # Unless the player has pressed the Start button, the Guess button will be disabled
    guessButton.Disable()
    nextButton = wx.Button(bkg, label='Start')
    nextButton.Bind(wx.EVT_BUTTON, next)
    hintButton = wx.Button(bkg, label='Hint')
    hintButton.Bind(wx.EVT_BUTTON, hint)
    hintButton.Disable()
    input_word = wx.TextCtrl(bkg)
    question = wx.StaticText(bkg, label="Welcome to jumbled words game\nTotal words: 25", style=wx.ALIGN_CENTER)
    # We define some stylish fonts for the welcome message / game questions
    font = wx.Font(pointSize=18, family=wx.DECORATIVE, style=wx.NORMAL, weight=wx.NORMAL)
    question.SetFont(font)
    result = wx.StaticText(bkg, label="Waiting for the initial result...", style=wx.ALIGN_CENTER)
    hbox = wx.BoxSizer()
    hbox.Add(input_word, proportion=1, flag=wx.EXPAND)
    hbox.Add(guessButton, proportion=0, flag=wx.LEFT, border=5)
    hbox.Add(nextButton, proportion=0, flag=wx.LEFT, border=5)
    hbox.Add(hintButton, proportion=0, flag=wx.LEFT, border=5)
    vbox = wx.BoxSizer(wx.VERTICAL)
    vbox.Add(question, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
    vbox.Add(hbox, proportion=0, flag=wx.EXPAND | wx.LEFT | wx.BOTTOM | wx.RIGHT, border=5)
    vbox.Add(result, proportion=0, flag=wx.EXPAND | wx.LEFT | wx.BOTTOM | wx.RIGHT, border=5)
    bkg.SetSizer(vbox)
    win.Show()
    app.MainLoop()
  • To run it, open the command-line. In Windows, go to Start > Run. Type cmd. In Linux, open Terminal is GNOME or Konsole in KDE. Then cd (move) to the location of the folder containing the file JumbledGUI.py. After that, type python JumbledGUI.py and enjoy playing with the just created application.
  • Now that you just ran it, what if you wanted to show it to your friend? Would it look good if he had to issue the command in the command-line just for running it? No? You are right. Now is the time to publish it!
  • You’ll publish it by making an executable out of it (that .exe file which runs on double-clicking). With this step, I am going specific for just the Windows users. I’ll come to the Linux method of creating an executable some time later. To make an executable from your Python file, download and install py2exe from here: http://sourceforge.net/project/showfiles.php?group_id=15583.
  • Create a new file in the same folder as JumbledGUI.py, copy-paste the following content, and save it with the name setup.py.
  • # Requires wxPython.  This sample demonstrates:
    #
    # - single file exe using wxPython as GUI.from distutils.core import setup
    import py2exe
    import sys</span>
     
    # If run without args, build executables, in quiet mode.
    if len(sys.argv) == 1:
    sys.argv.append("py2exe")
    sys.argv.append("-q")
     
    class Target:
    def __init__(self, **kw):
    self.__dict__.update(kw)
    # for the versioninfo resources
    self.version = "1.1"
    self.company_name = "Anurag Bhandari"
    self.copyright = "GPL v2"
    self.name = "Jumbled Words Game"
     
    ################################################################
    # A program using wxPython
     
    # The manifest will be inserted as resource into JumbledGUI.exe.  This
    # gives the controls the Windows XP appearance (if run on XP ;-)
    #
    # Another option would be to store it in a file named
    # JumbledGUI.exe.manifest, and copy it with the data_files option into
    # the dist-dir.
    #
    manifest_template = '''
     
    %(prog)s Program
     
    RT_MANIFEST = 24
     
    JumbledGUI = Target(
    # used for the versioninfo resource
    description = "A cute jumbled words game",
     
    # what to build
    script = "JumbledGUI.py",
    other_resources = [(RT_MANIFEST, 1, manifest_template % dict(prog="JumbledGUI"))],
    # icon_resources = [(1, "icon.ico")],
    dest_base = "JumbledGUI")
     
    ################################################################
     
    setup(
    options = {"py2exe": {"compressed": 1,
    "optimize": 2,
    "ascii": 1,
    "bundle_files": 1}},
    zipfile = None,
    windows = [JumbledGUI],
    )
  • It’s time to modify the publishing information of the to-be-created exe. Open setup.py and look for the code: Replace the self.version, self.company_name, self.copyright and self.name values with your desired values.
  • Now you are ready to “build” the exe. For that, open command prompt, cd to the folder where the setup.py file is placed (the same location as JumbledGUI.py) and issue the command: python setup.py py2exe.
  • This will create two folders where your two Python files are placed. One is the dist folder and the other is the build folder. Our folder of interest is the dist folder.
  • Open the dist folder and look for the just created exe file. Double click it and viola! It works!
  • To give your application a more professional touch, you may opt to created a setup of your program so that the end users are able to install it the way they install other softwares (the Next, Next, Next way…). For that, download the Inno Setup software from: http://www.jrsoftware.org/isinfo.php.

It was fun, wasn’t it?

I’ve provided comments in the code at all possible places so you don’t find it difficult to know what has been done there. I admit not using much efficient code, like making use of classes than just pure functions, but I’ll try to modify the code and rewrite it with classes as soon as I get some time for it.

I’ll post my own created setup for this app soon. 🙂

4 thoughts on “Jumbled Words game in Python

  1. […] promised in my last post about my Python-based jumbled words game, here I am posting the game for download in various forms. As of now, the first and second forms […]

  2. […] promised in my last post about my Python-based jumbled words game, here I am posting the game for download in various forms. As of now, the first and second forms […]

  3. […] am also working on improving the Jumbled Words game I prepared in Python some time […]

  4. […] the little, cute Jumbled Words Game I prepared in Python? More than 4 months had passed since I made it, and now it was time it got […]

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.