#100DaysOfCode: Python Day 21

#100DaysOfCode: Python Day 21

Building Snake (Part 2)

ยท

2 min read

#100DaysOfCode Day 21

๐Ÿ I CREATED MY OWN SNAKE GAME! ๐Ÿ
CLICK HERE and press "Run" to try it out.
Screenshot 2021-05-31 at 20.09.04.png

Yesterday I created completed my own snake game. While it is not very playable on Replit, if you download the code, it runs way better! I also learned how to use class inheritance and slicing.

Lessons

  1. Replit is not all that great for GUI games.
  2. If you following OOP and not using inheritance, you have so much more to gain.
    Always try and follow the DRY principle (Don't Repeat Yourself).

TO THE CODE!!!

# Class Inheritance
# Allows us to extend functionality without reinventing the wheel!


class Animal:
    def __init__(self):
        self.num_eyes = 2

    def breathe(self):
        print("Inhale, exhale.")


# This is how we inherit from Animal
# The super().__init__ initialises everything that is in the super class
class Fish(Animal):
    def __init__(self):
        super().__init__()

    def breathe(self):
        # This line allows everything in the super class breath function to run
        super().breathe()
        # This will run if the animal is a fish
        print("doing this underwater.")

    # This is something unique that only a fish can do but not an animal
    def swim(self):
        print("moving in water.")


nemo = Fish()
nemo.swim()
nemo.breathe()
print(f"num of eyes {nemo.num_eyes}")

# OUTPUT:
# moving in water.
# Inhale, exhale.
# doing this underwater.
# num of eyes 2

#########################

# Slicing
# Note this also works for tuples and not only lists
piano_keys = ["a", "b", "c", "d", "e", "f", "g"]

# Get all values from index 2
print(piano_keys[2:])
# OUTPUT:
# ['c', 'd', 'e', 'f', 'g']

# Gets index 1 to 3 leaving out 4
print(piano_keys[1:4])
# OUTPUT:
# ['b', 'c', 'd']

# Gets index 1 to 5 but every second interval
print(piano_keys[1:5:2])
# OUTPUT:
# ['b', 'd']

I had fun using Replit, but I may need to upload my code in zip files for you to try out in future.

Want to stay up to date with my learning journey? Just sign up for my newsletter.