DEV Community

dongdiri
dongdiri

Posted on

DAY14:Python day 19, 20, 21

Day 19

event listeners and higher order functions

  • it a higher-order function (functions that can work with other functions)
  • in a higher-order function, we don't add () for parameter function, we only pass the name.
high_order_function(function2)

screen.onkey(key="space", fun=move_forward) 
Enter fullscreen mode Exit fullscreen mode
  • creating separate objects from same class that have independent states (attributes, methods)

Day20: making the snake game

update() method to animate

  • turn off tracer screen.tracer[0]
  • control by importing time and delay through time.sleep()
  • then update screen when necessary by screen.update()

how do we turn our snake?

  • in order to prevent the body from leaving its head, we need to start from the last segment and make each segment occupy the position of its previous segment. The head moves last. This part was hard to come up with myself.
  • we do this by this for loop:
        for segment_number in range(len(self.segments) - 1, 0, -1):
            new_x = self.segments[segment_number - 1].xcor()
            new_y = self.segments[segment_number - 1].ycor()
            self.segments[segment_number].goto(new_x, new_y)
        self.segments[0].forward(move_distance)
Enter fullscreen mode Exit fullscreen mode
  • three parameters in range() function are start, stop, and step, respectively. So the order starts from the last, and decrements by 1 until it reaches 0, the head.

Day21: snake game continued

class inheritance

  • inheriting attributes/methods from parent(superclass)
class child(parent):
    def __init__(self):
        super().__init__()
Enter fullscreen mode Exit fullscreen mode

slicing

  • accessing set of items from one position to another
  • list[start position: end position: increment]
  • tip: list[::-1] to reverse the list

Top comments (0)