100일 간의 코드: 2022년을 위한 완벽한 Python Pro 부트캠프 - 21일차(스네이크 게임 2부)

23043 단어
  • 2일차 프로세스

  • 계승

    뱀 게임의 계속
  • 음식 충돌 감지
  • 스코어보드 생성 및 스코어 유지
  • 벽과의 충돌 감지
  • 꼬리와의 충돌 감지
  • 상속

  • 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(Fish, self).breathe()
            print("doing this under water")
    
        def swim(self):
            print("moving in water")
    
    
    nemo = Fish()
    nemo.swim()
    nemo.breathe()
    print(nemo.num_eyes)
    


  • 1. 음식과의 충돌 감지
    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 food import Food
    food = Food()
    if snake.head.distance(food) < 15:
        food.refresh()
    


    main.py 완료

    from turtle import Screen
    from snake import Snake
    from food import Food
    import time
    
    # Screen setup
    screen = Screen()
    screen.setup(width=600, height=600)
    screen.bgcolor("black")
    screen.title("SnakeGame")
    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()
    
        if snake.head.distance(food) < 15:
            food.refresh()
    
    screen.exitonclick()
    


  • 2. 점수판을 생성하고 점수를 유지

  • scoreboard.py 만들기

    from turtle import Turtle
    
    ALIGNMENT = "center"
    FONT = ("Courier", 20, "normal")
    
    
    class Scoreboard(Turtle):
    
        def __init__(self):
            super().__init__()
            self.hideturtle()
            self.score = 0
            self.penup()
            self.setx(0)
            self.sety(260)
            self.pendown()
            self.color("white")
            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 추가
    스코어보드에서 스코어보드 가져오기
    점수 = 스코어보드()
    if 문 아래에 score.increase_score()를 추가합니다.

    from turtle import Screen
    from snake import Snake
    from food import Food
    from scoreboard import Scoreboard
    import time
    
    # Screen setup
    screen = Screen()
    screen.setup(width=600, height=600)
    screen.bgcolor("black")
    screen.title("SnakeGame")
    screen.tracer(0)
    
    snake = Snake()
    food = Food()
    score = 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()
    
        if snake.head.distance(food) < 15:
            food.refresh()
            score.increase_score()
    
    screen.exitonclick()
    


  • 3 + 4 벽과 꼬리와의 충돌 감지
    뱀.py

  • class Snake:
    
        def __init__(self):
            self.all_snake = []
            self.create_snake()
            self.head = self.all_snake[0]
    
        def create_snake(self):
            for position in STARTING_POSITIONS:
                self.add_segment(position)
    
        def add_segment(self, position):
            new_snake = Turtle("square")
            new_snake.color("white")
            new_snake.penup()
            new_snake.goto(position)
            self.all_snake.append(new_snake)
    
        def extend(self):
            self.add_segment(self.all_snake[-1].position())
    


    main.py

    # Detect collision with tail
        for segment in snake.all_snake:
            if segment == snake.head:
                pass
            elif snake.head.distance(segment) < 10:
                game_is_on = False
                score.game_over()
    
        # 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
            score.game_over()
    

    좋은 웹페이지 즐겨찾기