Jonnie Grieve Digital Media: Blog

Home
by on 7th May, 2021 - 4:39pm (0)

Blog: R7D14: #100DaysOfCode (More Posts)

I’ve had another one of those days where responsibilities elsewhere have taken me away from coding and business matter for most of the day, but I did find some time to dig into some work with Python classes and creating a memory game for practice.

Something that would utilise the knowledge I’ve gained in the last few days. Things like built-in methods and how they’re used in Python classes; how to use python class attributes, instance attributes, and methods.

So this memory game is fairly straightforward. It’s one of those things you’ve probably seen before where you pick 2 cards and see if they’re a face matching pair.

It requires at least 2 classes in 2 files.

  • Game.py
  • Cards.py

The implementation of this command-line program is nice and simple to begin with (it’s going to get more complicated and involved I’m sure). The card class takes 2 arguments in its __init__ method with self, referring to the instance of the class that was created. Each class should have an “init” method.

This is how it looks

class Card: 
    def __init__(self, word, location): 
    self.word = word 
    self.location = location 
    self.matched = False
 

The next 2 methods prepare the groundwork for making the game readable by anyone who uses it. By using the __str__ “dunder” method to specify the name of the card being matched and the __eq__ to check that any two cards are the same.

def __eq__(self, other):
    return self.card == other.card

def __str__(self):
   return self.card

The next part is the main method that creates new instances of the Card class and is designed to test that the above 2 methods are working.

if __name__ == '__main__':
    card1 = Card('egg', 'A1')
    card2 = Card('egg', 'B1')
    card3 = Card('hut', 'D4')

As you can see 3 instances of Card have been created with 2 strings passed in as arguments.  The string representation of the card face and the location in the game “grid”.  That grid will be created in the Game class.

Finally to complete the class (for the time being at least we can print our instances to the console to check the results of our testing.

print(card1 == card2)
print(card1 == card3)
print(card2 == card3)
print(card1 == card2)
print(card1)

# returns the following results
True
False
False
True
egg

This is a start. There’s still the Game class to code which will be the home for the functionality of the game and program flow which I would imagine is going to take a lot of time and code.  I’m looking forward to spending more time on it in my next blog.

Related Links

https://teamtreehouse.com – OOP Python Programming

This post has been assigned to the following categories

    Leave a Reply

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