Inheritance
class Fish(Animal):
def __init__(self):
super().__init__()
all we have to do is to add a set of parentheses after the name of the calss and then provide the class that we want to inherit from.
So in this case our fish is inheriting from the animal
class.
And then in order to get a hold of everything that an animal
has and is, so its attributes and methods, all we have to do is inside the init
, add the super().__init__().
And the super
refers to the superclass.
So, basically, initialize everything that the superclass can do in our fish
class.
super().__init__().
class Animal:
def __init__(self):
self.num_eyes = 2
def breathe(self):
print("Inhale, exhale.")
class Fish(Animal):
def __init__(self):
super().__init__()
def breathe(self):
super().breathe()
print("doing this underwater.")
def swim(self):
print("moving in water.")
nemo = Fish()
nemo.breathe()
#output
Inhale, exhale.
doing this underwater.
Collisions with Food
food.py
from turtle import Turtle
import random
class Food(Turtle):
def __init__(self):
super().__init__()
self.shape("circle")
self.penup()
self.shapesize(stretch_len=0.5, stretch_wid=0.5)
self.color("blue")
self.speed("fastest")
random_x = random.randint(-280, 280)
random_y = random.randint(-280, 280)
self.goto(random_x, random_y)
whenever we initialize a new object from the class, the init get called.
food.py
from turtle import Turtle
import random
class Food(Turtle):
def __init__(self):
super().__init__()
self.shape("circle")
self.penup()
self.shapesize(stretch_len=0.5, stretch_wid=0.5)
self.color("blue")
self.speed("fastest")
self.refresh()
def refresh(self):
random_x = random.randint(-280, 280)
random_y = random.randint(-280, 280)
self.goto(random_x, random_y)
main.py
from turtle import Screen, Turtle
from snake import Snake
from food import Food
import time
screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("My Snake Game")
screen.tracer(0)
snake = Snake()
food = Food()
screen.listen()
screen.onkey(snake.up, "Up")
screen.onkey(snake.down, "Down")
screen.onkey(snake.left, "Left")
screen.onkey(snake.right, "Right")
game_is_on = True
while game_is_on:
screen.update()
time.sleep(0.1)
snake.move()
#Detect collision with food.
if snake.head.distance(food) < 15:
food.refresh()
screen.exitonclick()
.shapesize()
& .distance()
Create a Scoreboard and Keeps Score
scoreboard.py
from turtle import Turtle
ALIGNMENT = "center"
FONT = ("Courier", 24, "normal")
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.score = 0
self.color("white")
self.penup()
self.goto(0, 270)
self.hideturtle()
self.update_scoreboard()
def update_scoreboard(self):
self.write(f"Score: {self.score}", align=ALIGNMENT, font=FONT)
def increase_score(self):
self.score += 1
self.clear()
self.update_scoreboard()
main.py
from turtle import Screen, Turtle
from snake import Snake
from food import Food
from scoreboard import Scoreboard
import time
screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("My Snake Game")
screen.tracer(0)
snake = Snake()
food = Food()
scoreboard = Scoreboard()
screen.listen()
screen.onkey(snake.up, "Up")
screen.onkey(snake.down, "Down")
screen.onkey(snake.left, "Left")
screen.onkey(snake.right, "Right")
game_is_on = True
while game_is_on:
screen.update()
time.sleep(0.1)
snake.move()
# Detect collision with food.
if snake.head.distance(food) < 15:
food.refresh()
scoreboard.increase_score()
screen.exitonclick()
.write()
& .clear()
Detect Collision with the Wall
sccoreboard.py
from turtle import Turtle
ALIGNMENT = "center"
FONT = ("Courier", 24, "normal")
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.score = 0
self.color("white")
self.penup()
self.goto(0, 270)
self.hideturtle()
self.update_scoreboard()
def update_scoreboard(self):
self.write(f"Score: {self.score}", align=ALIGNMENT, font=FONT)
def game_over(self):
self.goto(0, 0)
self.write("GAME OVER", align=ALIGNMENT, font=FONT)
def increase_score(self):
self.score += 1
self.clear()
self.update_scoreboard()
main.py
from turtle import Screen, Turtle
from snake import Snake
from food import Food
from scoreboard import Scoreboard
import time
screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("My Snake Game")
screen.tracer(0)
snake = Snake()
food = Food()
scoreboard = Scoreboard()
screen.listen()
screen.onkey(snake.up, "Up")
screen.onkey(snake.down, "Down")
screen.onkey(snake.left, "Left")
screen.onkey(snake.right, "Right")
game_is_on = True
while game_is_on:
screen.update()
time.sleep(0.1)
snake.move()
# Detect collision with food.
if snake.head.distance(food) < 15:
food.refresh()
scoreboard.increase_score()
# Detect collision with wall.
if snake.head.xcor() > 280 or snake.head.xcor() < -280 or snake.head.ycor() > 280 or snake.head.ycor() < -280:
game_is_on = False
scoreboard.game_over()
screen.exitonclick()
Detect collision with tail
snake.py
from turtle import Turtle
STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)]
MOVE_DISTANCE = 20
UP = 90
DOWN = 270
LEFT = 180
RIGHT = 0
class Snake:
def __init__(self):
self.segments = []
self.create_snake()
self.head = self.segments[0]
def create_snake(self):
for position in STARTING_POSITIONS:
self.add_segment(position)
def add_segment(self, position):
new_segment = Turtle("square")
new_segment.color("white")
new_segment.penup()
new_segment.goto(position)
self.segments.append(new_segment)
def extend(self):
self.add_segment(self.segments[-1].position())
def move(self):
for seg_num in range(len(self.segments) - 1, 0, -1):
new_x = self.segments[seg_num - 1].xcor()
new_y = self.segments[seg_num - 1].ycor()
self.segments[seg_num].goto(new_x, new_y)
self.head.forward(MOVE_DISTANCE)
def up(self):
if self.head.heading() != DOWN:
self.head.setheading(UP)
def down(self):
if self.head.heading() != UP:
self.head.setheading(DOWN)
def left(self):
if self.head.heading() != RIGHT:
self.head.setheading(LEFT)
def right(self):
if self.head.heading() != LEFT:
self.head.setheading(RIGHT)
.position()
main.py
from turtle import Screen, Turtle
from snake import Snake
from food import Food
from scoreboard import Scoreboard
import time
screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("My Snake Game")
screen.tracer(0)
snake = Snake()
food = Food()
scoreboard = Scoreboard()
screen.listen()
screen.onkey(snake.up, "Up")
screen.onkey(snake.down, "Down")
screen.onkey(snake.left, "Left")
screen.onkey(snake.right, "Right")
game_is_on = True
while game_is_on:
screen.update()
time.sleep(0.1)
snake.move()
# Detect collision with food.
if snake.head.distance(food) < 15:
food.refresh()
snake.extend()
scoreboard.increase_score()
# Detect collision with wall.
if snake.head.xcor() > 280 or snake.head.xcor() < -280 or snake.head.ycor() > 280 or snake.head.ycor() < -280:
game_is_on = False
scoreboard.game_over()
# Detect collision with tail.
for segment in snake.segments:
# if head collision with any segment in the tail.
# trigger game_over
if segment == snake.segments:
pass
elif snake.head.distance(segment) < 10:
game_is_on = False
scoreboard.game_over()
screen.exitonclick()
Slice
piano_keys = ["a", "b", "c", "d", "e", "f", "g"]
piano_tuple = ("do", "re", "mi", "fa", "so", "la", "ti")
print(piano_keys[2:5])
print(piano_keys[:5])
print(piano_keys[2:])
print(piano_keys[2:5:2])
print(piano_keys[::2])
print(piano_keys[::-1])
#output
['c', 'd', 'e']
['a', 'b', 'c', 'd', 'e']
['c', 'd', 'e', 'f', 'g']
['c', 'e']
['a', 'c', 'e', 'g']
['g', 'f', 'e', 'd', 'c', 'b', 'a']
main.py
from turtle import Screen, Turtle
from snake import Snake
from food import Food
from scoreboard import Scoreboard
import time
screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("My Snake Game")
screen.tracer(0)
snake = Snake()
food = Food()
scoreboard = Scoreboard()
screen.listen()
screen.onkey(snake.up, "Up")
screen.onkey(snake.down, "Down")
screen.onkey(snake.left, "Left")
screen.onkey(snake.right, "Right")
game_is_on = True
while game_is_on:
screen.update()
time.sleep(0.1)
snake.move()
# Detect collision with food.
if snake.head.distance(food) < 15:
food.refresh()
snake.extend()
scoreboard.increase_score()
# Detect collision with wall.
if snake.head.xcor() > 280 or snake.head.xcor() < -280 or snake.head.ycor() > 280 or snake.head.ycor() < -280:
game_is_on = False
scoreboard.game_over()
# Detect collision with tail.
for segment in snake.segments[1:]:
if snake.head.distance(segment) < 10:
game_is_on = False
scoreboard.game_over()
screen.exitonclick()