This is an old revision of the document!
Table of Contents
PyBog
Let's talk about PyBog. The beginning should be easy at this point:
main.py
from myrandom import * from bog import * def main(): # First, we declare all the main variables # at the start of the program. list = [] # list of words for word search bog = make_bog() # the game board # Here, we will try to put five words into 'list', while len(list) < 5: a = random_n_3() if a not in list: # but only if they are not already there. list.append(a) # shuffle the list random.shuffle(list) # Try to fit the word on the board. #gamelist = [] #for word in list: # if not try_put_bog(bog, word, 1000): # gamelist.append(word) #list = gamelist list = [x for x in list if try_put_bog(bog, x, 1000)] fill_bog(bog) # fill up with random letters print_bog(bog) # display the board print(" ".join(list)) # display the words to find if __name__ == "__main__": main()
Look carefully at the code which iterates over the list, and uses a temporary variable, “gamelist”. This can be replaced by the code:
list = [x for x in list if try_put_bog(bog, x, 1000)]
This is a python specific way of filtering a list. You can use either method as you prefer. The longer approach works in most languages, but is considered clunky if a filtering method is available. However, thinking in this way is an important prerequisite in understanding algorithms in general, so you should understand and appreciate the first way even if you are using Python. It is important to get used to moving data around and processing it. In-place processing such as the 'one line solution' can sometimes lead to strange and unforseen results.
The real magic happens in the bog.py file. But first let's look at myrandom.
myrandom.py
import random def random_n_3(): nouns = [ "car", "dog", "cat", "man", "sun", "eye", "pen", "cup", "leg", "hat", "sky", "bus", "bed", "fly", "key", "map", "gun", "bag", "job", "boy", "top", "lip", "son", "toy", "law", "art", "box", "ear", "cow", "ice", "sea", "rat", "egg", "tie", "pie", "pig", "bee" ] n = random.choice(nouns) return n
This is just a file that gives us a list of random words. It's data, so I put it in a separate file.
I do not recommend you mix code and data. If you have a lot of data, try to separate it from the algorithms in your code. That way you can change the way you store and access the data later with minimal impact.
bog.py
This is where all the real magic happens. This could have been a class, but, since it's just a small, specialized project, I decided to write it using functions for kicks. Instead of self, I just use a bog variable. It's basically the same as if I wrote it like a class.