Lệnh rùa Python sao chép và dán

“Turtle” là một tính năng của trăn giống như một bảng vẽ, cho phép bạn ra lệnh cho một chú rùa vẽ lên đó

Bạn có thể sử dụng các chức năng như turtle.forward(...)

""" A simple snake game using Turtle Graphics. """
import turtle
import random

WIDTH = 500
HEIGHT = 500
FOOD_SIZE = 10
DELAY = 100  # milliseconds

offsets = {
    "up": (0, 20),
    "down": (0, -20),
    "left": (-20, 0),
    "right": (20, 0)
}

def reset():
    global snake, snake_direction, food_pos, pen
    snake = [[0, 0], [0, 20], [0, 40], [0, 60], [0, 80]]
    snake_direction = "up"
    food_pos = get_random_food_pos()
    food.goto(food_pos)
    # screen.update() Only needed if we are fussed about drawing food before next call to `draw_snake()`.
    move_snake()

def move_snake():
    global snake_direction

    #  Next position for head of snake.
    new_head = snake[-1].copy()
    new_head[0] = snake[-1][0] + offsets[snake_direction][0]
    new_head[1] = snake[-1][1] + offsets[snake_direction][1]

    # Check self-collision
    if new_head in snake[:-1]:  # Or collision with walls?
        reset()
    else:
        # No self-collision so we can continue moving the snake.
        snake.append(new_head)

        # Check food collision
        if not food_collision():
            snake.pop(0)  # Keep the snake the same length unless fed.

        #  Allow screen wrapping
        if snake[-1][0] > WIDTH / 2:
            snake[-1][0] -= WIDTH
        elif snake[-1][0] < - WIDTH / 2:
            snake[-1][0] += WIDTH
        elif snake[-1][1] > HEIGHT / 2:
            snake[-1][1] -= HEIGHT
        elif snake[-1][1] < -HEIGHT / 2:
            snake[-1][1] += HEIGHT

        # Clear previous snake stamps
        pen.clearstamps()

        # Draw snake
        for segment in snake:
            pen.goto(segment[0], segment[1])
            pen.stamp()

        # Refresh screen
        screen.update()

        # Rinse and repeat
        turtle.ontimer(move_snake, DELAY)

def food_collision():
    global food_pos
    if get_distance(snake[-1], food_pos) < 20:
        food_pos = get_random_food_pos()
        food.goto(food_pos)
        return True
    return False

def get_random_food_pos():
    x = random.randint(- WIDTH / 2 + FOOD_SIZE, WIDTH / 2 - FOOD_SIZE)
    y = random.randint(- HEIGHT / 2 + FOOD_SIZE, HEIGHT / 2 - FOOD_SIZE)
    return (x, y)

def get_distance(pos1, pos2):
    x1, y1 = pos1
    x2, y2 = pos2
    distance = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5
    return distance

def go_up():
    global snake_direction
    if snake_direction != "down":
        snake_direction = "up"

def go_right():
    global snake_direction
    if snake_direction != "left":
        snake_direction = "right"

def go_down():
    global snake_direction
    if snake_direction != "up":
        snake_direction = "down"

def go_left():
    global snake_direction
    if snake_direction != "right":
        snake_direction = "left"

# Screen
screen = turtle.Screen()
screen.setup(WIDTH, HEIGHT)
screen.title("Snake")
screen.bgcolor("green")
screen.setup(500, 500)
screen.tracer(0)

# Pen
pen = turtle.Turtle("square")
pen.penup()

# Food
food = turtle.Turtle()
food.shape("circle")
food.color("red")
food.shapesize(FOOD_SIZE / 20)  # Default size of turtle "square" shape is 20.
food.penup()

# Event handlers
screen.listen()
screen.onkey(go_up, "Up")
screen.onkey(go_right, "Right")
screen.onkey(go_down, "Down")
screen.onkey(go_left, "Left")

# Let's go
reset()
turtle.done()
0 để di chuyển con rùa xung quanh

Trước khi bạn có thể sử dụng rùa, bạn phải nhập nó. Trước tiên, chúng tôi khuyên bạn nên thử với nó trong trình thông dịch tương tác, vì cần thêm một chút công việc để làm cho nó hoạt động từ các tệp. Chỉ cần đi đến thiết bị đầu cuối của bạn và gõ

Lệnh rùa Python sao chép và dán

Ghi chú

Không thấy gì trên Mac OS?

Ghi chú

Bạn làm việc với Ubuntu và nhận được thông báo lỗi “No module named _tkinter”?

Ghi chú

Mặc dù việc sao chép và dán những gì được viết trên trang này vào thiết bị đầu cuối của bạn có thể rất hấp dẫn, nhưng chúng tôi khuyến khích bạn nhập từng lệnh. Gõ có cú pháp dưới ngón tay của bạn (xây dựng bộ nhớ cơ. ) và thậm chí có thể giúp tránh các lỗi cú pháp lạ

Lệnh rùa Python sao chép và dán
Lệnh rùa Python sao chép và dán

Hàm turtle.forward(...) yêu cầu con rùa di chuyển về phía trước theo khoảng cách đã cho.

""" A simple snake game using Turtle Graphics. """
import turtle
import random

WIDTH = 500
HEIGHT = 500
FOOD_SIZE = 10
DELAY = 100  # milliseconds

offsets = {
    "up": (0, 20),
    "down": (0, -20),
    "left": (-20, 0),
    "right": (20, 0)
}

def reset():
    global snake, snake_direction, food_pos, pen
    snake = [[0, 0], [0, 20], [0, 40], [0, 60], [0, 80]]
    snake_direction = "up"
    food_pos = get_random_food_pos()
    food.goto(food_pos)
    # screen.update() Only needed if we are fussed about drawing food before next call to `draw_snake()`.
    move_snake()

def move_snake():
    global snake_direction

    #  Next position for head of snake.
    new_head = snake[-1].copy()
    new_head[0] = snake[-1][0] + offsets[snake_direction][0]
    new_head[1] = snake[-1][1] + offsets[snake_direction][1]

    # Check self-collision
    if new_head in snake[:-1]:  # Or collision with walls?
        reset()
    else:
        # No self-collision so we can continue moving the snake.
        snake.append(new_head)

        # Check food collision
        if not food_collision():
            snake.pop(0)  # Keep the snake the same length unless fed.

        #  Allow screen wrapping
        if snake[-1][0] > WIDTH / 2:
            snake[-1][0] -= WIDTH
        elif snake[-1][0] < - WIDTH / 2:
            snake[-1][0] += WIDTH
        elif snake[-1][1] > HEIGHT / 2:
            snake[-1][1] -= HEIGHT
        elif snake[-1][1] < -HEIGHT / 2:
            snake[-1][1] += HEIGHT

        # Clear previous snake stamps
        pen.clearstamps()

        # Draw snake
        for segment in snake:
            pen.goto(segment[0], segment[1])
            pen.stamp()

        # Refresh screen
        screen.update()

        # Rinse and repeat
        turtle.ontimer(move_snake, DELAY)

def food_collision():
    global food_pos
    if get_distance(snake[-1], food_pos) < 20:
        food_pos = get_random_food_pos()
        food.goto(food_pos)
        return True
    return False

def get_random_food_pos():
    x = random.randint(- WIDTH / 2 + FOOD_SIZE, WIDTH / 2 - FOOD_SIZE)
    y = random.randint(- HEIGHT / 2 + FOOD_SIZE, HEIGHT / 2 - FOOD_SIZE)
    return (x, y)

def get_distance(pos1, pos2):
    x1, y1 = pos1
    x2, y2 = pos2
    distance = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5
    return distance

def go_up():
    global snake_direction
    if snake_direction != "down":
        snake_direction = "up"

def go_right():
    global snake_direction
    if snake_direction != "left":
        snake_direction = "right"

def go_down():
    global snake_direction
    if snake_direction != "up":
        snake_direction = "down"

def go_left():
    global snake_direction
    if snake_direction != "right":
        snake_direction = "left"

# Screen
screen = turtle.Screen()
screen.setup(WIDTH, HEIGHT)
screen.title("Snake")
screen.bgcolor("green")
screen.setup(500, 500)
screen.tracer(0)

# Pen
pen = turtle.Turtle("square")
pen.penup()

# Food
food = turtle.Turtle()
food.shape("circle")
food.color("red")
food.shapesize(FOOD_SIZE / 20)  # Default size of turtle "square" shape is 20.
food.penup()

# Event handlers
screen.listen()
screen.onkey(go_up, "Up")
screen.onkey(go_right, "Right")
screen.onkey(go_down, "Down")
screen.onkey(go_left, "Left")

# Let's go
reset()
turtle.done()
0 mất một số độ mà bạn muốn xoay sang trái. Ngoài ra còn có
""" A simple snake game using Turtle Graphics. """
import turtle
import random

WIDTH = 500
HEIGHT = 500
FOOD_SIZE = 10
DELAY = 100  # milliseconds

offsets = {
    "up": (0, 20),
    "down": (0, -20),
    "left": (-20, 0),
    "right": (20, 0)
}

def reset():
    global snake, snake_direction, food_pos, pen
    snake = [[0, 0], [0, 20], [0, 40], [0, 60], [0, 80]]
    snake_direction = "up"
    food_pos = get_random_food_pos()
    food.goto(food_pos)
    # screen.update() Only needed if we are fussed about drawing food before next call to `draw_snake()`.
    move_snake()

def move_snake():
    global snake_direction

    #  Next position for head of snake.
    new_head = snake[-1].copy()
    new_head[0] = snake[-1][0] + offsets[snake_direction][0]
    new_head[1] = snake[-1][1] + offsets[snake_direction][1]

    # Check self-collision
    if new_head in snake[:-1]:  # Or collision with walls?
        reset()
    else:
        # No self-collision so we can continue moving the snake.
        snake.append(new_head)

        # Check food collision
        if not food_collision():
            snake.pop(0)  # Keep the snake the same length unless fed.

        #  Allow screen wrapping
        if snake[-1][0] > WIDTH / 2:
            snake[-1][0] -= WIDTH
        elif snake[-1][0] < - WIDTH / 2:
            snake[-1][0] += WIDTH
        elif snake[-1][1] > HEIGHT / 2:
            snake[-1][1] -= HEIGHT
        elif snake[-1][1] < -HEIGHT / 2:
            snake[-1][1] += HEIGHT

        # Clear previous snake stamps
        pen.clearstamps()

        # Draw snake
        for segment in snake:
            pen.goto(segment[0], segment[1])
            pen.stamp()

        # Refresh screen
        screen.update()

        # Rinse and repeat
        turtle.ontimer(move_snake, DELAY)

def food_collision():
    global food_pos
    if get_distance(snake[-1], food_pos) < 20:
        food_pos = get_random_food_pos()
        food.goto(food_pos)
        return True
    return False

def get_random_food_pos():
    x = random.randint(- WIDTH / 2 + FOOD_SIZE, WIDTH / 2 - FOOD_SIZE)
    y = random.randint(- HEIGHT / 2 + FOOD_SIZE, HEIGHT / 2 - FOOD_SIZE)
    return (x, y)

def get_distance(pos1, pos2):
    x1, y1 = pos1
    x2, y2 = pos2
    distance = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5
    return distance

def go_up():
    global snake_direction
    if snake_direction != "down":
        snake_direction = "up"

def go_right():
    global snake_direction
    if snake_direction != "left":
        snake_direction = "right"

def go_down():
    global snake_direction
    if snake_direction != "up":
        snake_direction = "down"

def go_left():
    global snake_direction
    if snake_direction != "right":
        snake_direction = "left"

# Screen
screen = turtle.Screen()
screen.setup(WIDTH, HEIGHT)
screen.title("Snake")
screen.bgcolor("green")
screen.setup(500, 500)
screen.tracer(0)

# Pen
pen = turtle.Turtle("square")
pen.penup()

# Food
food = turtle.Turtle()
food.shape("circle")
food.color("red")
food.shapesize(FOOD_SIZE / 20)  # Default size of turtle "square" shape is 20.
food.penup()

# Event handlers
screen.listen()
screen.onkey(go_up, "Up")
screen.onkey(go_right, "Right")
screen.onkey(go_down, "Down")
screen.onkey(go_left, "Left")

# Let's go
reset()
turtle.done()
5 và
""" A simple snake game using Turtle Graphics. """
import turtle
import random

WIDTH = 500
HEIGHT = 500
FOOD_SIZE = 10
DELAY = 100  # milliseconds

offsets = {
    "up": (0, 20),
    "down": (0, -20),
    "left": (-20, 0),
    "right": (20, 0)
}

def reset():
    global snake, snake_direction, food_pos, pen
    snake = [[0, 0], [0, 20], [0, 40], [0, 60], [0, 80]]
    snake_direction = "up"
    food_pos = get_random_food_pos()
    food.goto(food_pos)
    # screen.update() Only needed if we are fussed about drawing food before next call to `draw_snake()`.
    move_snake()

def move_snake():
    global snake_direction

    #  Next position for head of snake.
    new_head = snake[-1].copy()
    new_head[0] = snake[-1][0] + offsets[snake_direction][0]
    new_head[1] = snake[-1][1] + offsets[snake_direction][1]

    # Check self-collision
    if new_head in snake[:-1]:  # Or collision with walls?
        reset()
    else:
        # No self-collision so we can continue moving the snake.
        snake.append(new_head)

        # Check food collision
        if not food_collision():
            snake.pop(0)  # Keep the snake the same length unless fed.

        #  Allow screen wrapping
        if snake[-1][0] > WIDTH / 2:
            snake[-1][0] -= WIDTH
        elif snake[-1][0] < - WIDTH / 2:
            snake[-1][0] += WIDTH
        elif snake[-1][1] > HEIGHT / 2:
            snake[-1][1] -= HEIGHT
        elif snake[-1][1] < -HEIGHT / 2:
            snake[-1][1] += HEIGHT

        # Clear previous snake stamps
        pen.clearstamps()

        # Draw snake
        for segment in snake:
            pen.goto(segment[0], segment[1])
            pen.stamp()

        # Refresh screen
        screen.update()

        # Rinse and repeat
        turtle.ontimer(move_snake, DELAY)

def food_collision():
    global food_pos
    if get_distance(snake[-1], food_pos) < 20:
        food_pos = get_random_food_pos()
        food.goto(food_pos)
        return True
    return False

def get_random_food_pos():
    x = random.randint(- WIDTH / 2 + FOOD_SIZE, WIDTH / 2 - FOOD_SIZE)
    y = random.randint(- HEIGHT / 2 + FOOD_SIZE, HEIGHT / 2 - FOOD_SIZE)
    return (x, y)

def get_distance(pos1, pos2):
    x1, y1 = pos1
    x2, y2 = pos2
    distance = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5
    return distance

def go_up():
    global snake_direction
    if snake_direction != "down":
        snake_direction = "up"

def go_right():
    global snake_direction
    if snake_direction != "left":
        snake_direction = "right"

def go_down():
    global snake_direction
    if snake_direction != "up":
        snake_direction = "down"

def go_left():
    global snake_direction
    if snake_direction != "right":
        snake_direction = "left"

# Screen
screen = turtle.Screen()
screen.setup(WIDTH, HEIGHT)
screen.title("Snake")
screen.bgcolor("green")
screen.setup(500, 500)
screen.tracer(0)

# Pen
pen = turtle.Turtle("square")
pen.penup()

# Food
food = turtle.Turtle()
food.shape("circle")
food.color("red")
food.shapesize(FOOD_SIZE / 20)  # Default size of turtle "square" shape is 20.
food.penup()

# Event handlers
screen.listen()
screen.onkey(go_up, "Up")
screen.onkey(go_right, "Right")
screen.onkey(go_down, "Down")
screen.onkey(go_left, "Left")

# Let's go
reset()
turtle.done()
6 nữa

Ghi chú

Bạn muốn bắt đầu mới? . Chúng tôi sẽ đi vào chi tiết hơn về

""" A simple snake game using Turtle Graphics. """
import turtle
import random

WIDTH = 500
HEIGHT = 500
FOOD_SIZE = 10
DELAY = 100  # milliseconds

offsets = {
    "up": (0, 20),
    "down": (0, -20),
    "left": (-20, 0),
    "right": (20, 0)
}

def reset():
    global snake, snake_direction, food_pos, pen
    snake = [[0, 0], [0, 20], [0, 40], [0, 60], [0, 80]]
    snake_direction = "up"
    food_pos = get_random_food_pos()
    food.goto(food_pos)
    # screen.update() Only needed if we are fussed about drawing food before next call to `draw_snake()`.
    move_snake()

def move_snake():
    global snake_direction

    #  Next position for head of snake.
    new_head = snake[-1].copy()
    new_head[0] = snake[-1][0] + offsets[snake_direction][0]
    new_head[1] = snake[-1][1] + offsets[snake_direction][1]

    # Check self-collision
    if new_head in snake[:-1]:  # Or collision with walls?
        reset()
    else:
        # No self-collision so we can continue moving the snake.
        snake.append(new_head)

        # Check food collision
        if not food_collision():
            snake.pop(0)  # Keep the snake the same length unless fed.

        #  Allow screen wrapping
        if snake[-1][0] > WIDTH / 2:
            snake[-1][0] -= WIDTH
        elif snake[-1][0] < - WIDTH / 2:
            snake[-1][0] += WIDTH
        elif snake[-1][1] > HEIGHT / 2:
            snake[-1][1] -= HEIGHT
        elif snake[-1][1] < -HEIGHT / 2:
            snake[-1][1] += HEIGHT

        # Clear previous snake stamps
        pen.clearstamps()

        # Draw snake
        for segment in snake:
            pen.goto(segment[0], segment[1])
            pen.stamp()

        # Refresh screen
        screen.update()

        # Rinse and repeat
        turtle.ontimer(move_snake, DELAY)

def food_collision():
    global food_pos
    if get_distance(snake[-1], food_pos) < 20:
        food_pos = get_random_food_pos()
        food.goto(food_pos)
        return True
    return False

def get_random_food_pos():
    x = random.randint(- WIDTH / 2 + FOOD_SIZE, WIDTH / 2 - FOOD_SIZE)
    y = random.randint(- HEIGHT / 2 + FOOD_SIZE, HEIGHT / 2 - FOOD_SIZE)
    return (x, y)

def get_distance(pos1, pos2):
    x1, y1 = pos1
    x2, y2 = pos2
    distance = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5
    return distance

def go_up():
    global snake_direction
    if snake_direction != "down":
        snake_direction = "up"

def go_right():
    global snake_direction
    if snake_direction != "left":
        snake_direction = "right"

def go_down():
    global snake_direction
    if snake_direction != "up":
        snake_direction = "down"

def go_left():
    global snake_direction
    if snake_direction != "right":
        snake_direction = "left"

# Screen
screen = turtle.Screen()
screen.setup(WIDTH, HEIGHT)
screen.title("Snake")
screen.bgcolor("green")
screen.setup(500, 500)
screen.tracer(0)

# Pen
pen = turtle.Turtle("square")
pen.penup()

# Food
food = turtle.Turtle()
food.shape("circle")
food.color("red")
food.shapesize(FOOD_SIZE / 20)  # Default size of turtle "square" shape is 20.
food.penup()

# Event handlers
screen.listen()
screen.onkey(go_up, "Up")
screen.onkey(go_right, "Right")
screen.onkey(go_down, "Down")
screen.onkey(go_left, "Left")

# Let's go
reset()
turtle.done()
7 trong giây lát

Con rùa tiêu chuẩn chỉ là một hình tam giác. Đó không phải là niềm vui. Thay vào đó, hãy biến nó thành một con rùa bằng lệnh turtle.forward(...)2

dễ thương hơn nhiều

Nếu bạn đặt các lệnh vào một tệp, bạn có thể nhận ra rằng cửa sổ con rùa sẽ biến mất sau khi con rùa kết thúc chuyển động của nó. (Đó là do Python thoát ra khi rùa của bạn di chuyển xong. Vì cửa sổ con rùa thuộc về Python nên nó cũng biến mất. ) Để ngăn chặn điều đó, chỉ cần đặt turtle.forward(...)3 ở cuối tệp của bạn. Bây giờ cửa sổ vẫn mở cho đến khi bạn nhấp vào nó

import turtle

turtle.shape("turtle")

turtle.forward(25)

turtle.exitonclick()

Ghi chú

Python là ngôn ngữ lập trình trong đó việc thụt lề văn bản theo chiều ngang là quan trọng. Chúng ta sẽ tìm hiểu tất cả về điều này trong chương Hàm ở phần sau, nhưng bây giờ, hãy nhớ rằng các dấu cách hoặc tab đi lạc trước bất kỳ dòng mã Python nào cũng có thể gây ra lỗi không mong muốn. Bạn thậm chí có thể thử thêm một cái để kiểm tra xem python sẽ phàn nàn như thế nào

Đồ họa rùa Python thật tuyệt vời. Nó có thể được sử dụng để học và dạy lập trình Python và Khoa học máy tính từ trình độ cơ bản đến nâng cao. Có một [bài đăng trên blog của tôi] [1] về các bản trình diễn Đồ họa rùa đi kèm với IDLE (môi trường phát triển đi kèm với Python) - hãy xem chúng để có ý tưởng về một số điều thú vị mà bạn có thể làm

Bạn có thể chơi phiên bản [Trò chơi rắn cổ điển khi thay thế. nó ở đây. ][2]

Nhấp vào cửa sổ Rùa để bật điều khiển bàn phím bằng các phím mũi tên

Lệnh rùa Python sao chép và dán

Giải thích chương trình trò chơi rắn Python

rắn đại diện

Chúng tôi biểu diễn con rắn của mình dưới dạng danh sách các cặp tọa độ

""" A simple snake game using Turtle Graphics. """
import turtle
import random

WIDTH = 500
HEIGHT = 500
FOOD_SIZE = 10
DELAY = 100  # milliseconds

offsets = {
    "up": (0, 20),
    "down": (0, -20),
    "left": (-20, 0),
    "right": (20, 0)
}

def reset():
    global snake, snake_direction, food_pos, pen
    snake = [[0, 0], [0, 20], [0, 40], [0, 60], [0, 80]]
    snake_direction = "up"
    food_pos = get_random_food_pos()
    food.goto(food_pos)
    # screen.update() Only needed if we are fussed about drawing food before next call to `draw_snake()`.
    move_snake()

def move_snake():
    global snake_direction

    #  Next position for head of snake.
    new_head = snake[-1].copy()
    new_head[0] = snake[-1][0] + offsets[snake_direction][0]
    new_head[1] = snake[-1][1] + offsets[snake_direction][1]

    # Check self-collision
    if new_head in snake[:-1]:  # Or collision with walls?
        reset()
    else:
        # No self-collision so we can continue moving the snake.
        snake.append(new_head)

        # Check food collision
        if not food_collision():
            snake.pop(0)  # Keep the snake the same length unless fed.

        #  Allow screen wrapping
        if snake[-1][0] > WIDTH / 2:
            snake[-1][0] -= WIDTH
        elif snake[-1][0] < - WIDTH / 2:
            snake[-1][0] += WIDTH
        elif snake[-1][1] > HEIGHT / 2:
            snake[-1][1] -= HEIGHT
        elif snake[-1][1] < -HEIGHT / 2:
            snake[-1][1] += HEIGHT

        # Clear previous snake stamps
        pen.clearstamps()

        # Draw snake
        for segment in snake:
            pen.goto(segment[0], segment[1])
            pen.stamp()

        # Refresh screen
        screen.update()

        # Rinse and repeat
        turtle.ontimer(move_snake, DELAY)

def food_collision():
    global food_pos
    if get_distance(snake[-1], food_pos) < 20:
        food_pos = get_random_food_pos()
        food.goto(food_pos)
        return True
    return False

def get_random_food_pos():
    x = random.randint(- WIDTH / 2 + FOOD_SIZE, WIDTH / 2 - FOOD_SIZE)
    y = random.randint(- HEIGHT / 2 + FOOD_SIZE, HEIGHT / 2 - FOOD_SIZE)
    return (x, y)

def get_distance(pos1, pos2):
    x1, y1 = pos1
    x2, y2 = pos2
    distance = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5
    return distance

def go_up():
    global snake_direction
    if snake_direction != "down":
        snake_direction = "up"

def go_right():
    global snake_direction
    if snake_direction != "left":
        snake_direction = "right"

def go_down():
    global snake_direction
    if snake_direction != "up":
        snake_direction = "down"

def go_left():
    global snake_direction
    if snake_direction != "right":
        snake_direction = "left"

# Screen
screen = turtle.Screen()
screen.setup(WIDTH, HEIGHT)
screen.title("Snake")
screen.bgcolor("green")
screen.setup(500, 500)
screen.tracer(0)

# Pen
pen = turtle.Turtle("square")
pen.penup()

# Food
food = turtle.Turtle()
food.shape("circle")
food.color("red")
food.shapesize(FOOD_SIZE / 20)  # Default size of turtle "square" shape is 20.
food.penup()

# Event handlers
screen.listen()
screen.onkey(go_up, "Up")
screen.onkey(go_right, "Right")
screen.onkey(go_down, "Down")
screen.onkey(go_left, "Left")

# Let's go
reset()
turtle.done()
2

Chúng ta có thể sử dụng

""" A simple snake game using Turtle Graphics. """
import turtle
import random

WIDTH = 500
HEIGHT = 500
FOOD_SIZE = 10
DELAY = 100  # milliseconds

offsets = {
    "up": (0, 20),
    "down": (0, -20),
    "left": (-20, 0),
    "right": (20, 0)
}

def reset():
    global snake, snake_direction, food_pos, pen
    snake = [[0, 0], [0, 20], [0, 40], [0, 60], [0, 80]]
    snake_direction = "up"
    food_pos = get_random_food_pos()
    food.goto(food_pos)
    # screen.update() Only needed if we are fussed about drawing food before next call to `draw_snake()`.
    move_snake()

def move_snake():
    global snake_direction

    #  Next position for head of snake.
    new_head = snake[-1].copy()
    new_head[0] = snake[-1][0] + offsets[snake_direction][0]
    new_head[1] = snake[-1][1] + offsets[snake_direction][1]

    # Check self-collision
    if new_head in snake[:-1]:  # Or collision with walls?
        reset()
    else:
        # No self-collision so we can continue moving the snake.
        snake.append(new_head)

        # Check food collision
        if not food_collision():
            snake.pop(0)  # Keep the snake the same length unless fed.

        #  Allow screen wrapping
        if snake[-1][0] > WIDTH / 2:
            snake[-1][0] -= WIDTH
        elif snake[-1][0] < - WIDTH / 2:
            snake[-1][0] += WIDTH
        elif snake[-1][1] > HEIGHT / 2:
            snake[-1][1] -= HEIGHT
        elif snake[-1][1] < -HEIGHT / 2:
            snake[-1][1] += HEIGHT

        # Clear previous snake stamps
        pen.clearstamps()

        # Draw snake
        for segment in snake:
            pen.goto(segment[0], segment[1])
            pen.stamp()

        # Refresh screen
        screen.update()

        # Rinse and repeat
        turtle.ontimer(move_snake, DELAY)

def food_collision():
    global food_pos
    if get_distance(snake[-1], food_pos) < 20:
        food_pos = get_random_food_pos()
        food.goto(food_pos)
        return True
    return False

def get_random_food_pos():
    x = random.randint(- WIDTH / 2 + FOOD_SIZE, WIDTH / 2 - FOOD_SIZE)
    y = random.randint(- HEIGHT / 2 + FOOD_SIZE, HEIGHT / 2 - FOOD_SIZE)
    return (x, y)

def get_distance(pos1, pos2):
    x1, y1 = pos1
    x2, y2 = pos2
    distance = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5
    return distance

def go_up():
    global snake_direction
    if snake_direction != "down":
        snake_direction = "up"

def go_right():
    global snake_direction
    if snake_direction != "left":
        snake_direction = "right"

def go_down():
    global snake_direction
    if snake_direction != "up":
        snake_direction = "down"

def go_left():
    global snake_direction
    if snake_direction != "right":
        snake_direction = "left"

# Screen
screen = turtle.Screen()
screen.setup(WIDTH, HEIGHT)
screen.title("Snake")
screen.bgcolor("green")
screen.setup(500, 500)
screen.tracer(0)

# Pen
pen = turtle.Turtle("square")
pen.penup()

# Food
food = turtle.Turtle()
food.shape("circle")
food.color("red")
food.shapesize(FOOD_SIZE / 20)  # Default size of turtle "square" shape is 20.
food.penup()

# Event handlers
screen.listen()
screen.onkey(go_up, "Up")
screen.onkey(go_right, "Right")
screen.onkey(go_down, "Down")
screen.onkey(go_left, "Left")

# Let's go
reset()
turtle.done()
3 để ghi chú đoạn thứ n

""" A simple snake game using Turtle Graphics. """
import turtle
import random

WIDTH = 500
HEIGHT = 500
FOOD_SIZE = 10
DELAY = 100  # milliseconds

offsets = {
    "up": (0, 20),
    "down": (0, -20),
    "left": (-20, 0),
    "right": (20, 0)
}

def reset():
    global snake, snake_direction, food_pos, pen
    snake = [[0, 0], [0, 20], [0, 40], [0, 60], [0, 80]]
    snake_direction = "up"
    food_pos = get_random_food_pos()
    food.goto(food_pos)
    # screen.update() Only needed if we are fussed about drawing food before next call to `draw_snake()`.
    move_snake()

def move_snake():
    global snake_direction

    #  Next position for head of snake.
    new_head = snake[-1].copy()
    new_head[0] = snake[-1][0] + offsets[snake_direction][0]
    new_head[1] = snake[-1][1] + offsets[snake_direction][1]

    # Check self-collision
    if new_head in snake[:-1]:  # Or collision with walls?
        reset()
    else:
        # No self-collision so we can continue moving the snake.
        snake.append(new_head)

        # Check food collision
        if not food_collision():
            snake.pop(0)  # Keep the snake the same length unless fed.

        #  Allow screen wrapping
        if snake[-1][0] > WIDTH / 2:
            snake[-1][0] -= WIDTH
        elif snake[-1][0] < - WIDTH / 2:
            snake[-1][0] += WIDTH
        elif snake[-1][1] > HEIGHT / 2:
            snake[-1][1] -= HEIGHT
        elif snake[-1][1] < -HEIGHT / 2:
            snake[-1][1] += HEIGHT

        # Clear previous snake stamps
        pen.clearstamps()

        # Draw snake
        for segment in snake:
            pen.goto(segment[0], segment[1])
            pen.stamp()

        # Refresh screen
        screen.update()

        # Rinse and repeat
        turtle.ontimer(move_snake, DELAY)

def food_collision():
    global food_pos
    if get_distance(snake[-1], food_pos) < 20:
        food_pos = get_random_food_pos()
        food.goto(food_pos)
        return True
    return False

def get_random_food_pos():
    x = random.randint(- WIDTH / 2 + FOOD_SIZE, WIDTH / 2 - FOOD_SIZE)
    y = random.randint(- HEIGHT / 2 + FOOD_SIZE, HEIGHT / 2 - FOOD_SIZE)
    return (x, y)

def get_distance(pos1, pos2):
    x1, y1 = pos1
    x2, y2 = pos2
    distance = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5
    return distance

def go_up():
    global snake_direction
    if snake_direction != "down":
        snake_direction = "up"

def go_right():
    global snake_direction
    if snake_direction != "left":
        snake_direction = "right"

def go_down():
    global snake_direction
    if snake_direction != "up":
        snake_direction = "down"

def go_left():
    global snake_direction
    if snake_direction != "right":
        snake_direction = "left"

# Screen
screen = turtle.Screen()
screen.setup(WIDTH, HEIGHT)
screen.title("Snake")
screen.bgcolor("green")
screen.setup(500, 500)
screen.tracer(0)

# Pen
pen = turtle.Turtle("square")
pen.penup()

# Food
food = turtle.Turtle()
food.shape("circle")
food.color("red")
food.shapesize(FOOD_SIZE / 20)  # Default size of turtle "square" shape is 20.
food.penup()

# Event handlers
screen.listen()
screen.onkey(go_up, "Up")
screen.onkey(go_right, "Right")
screen.onkey(go_down, "Down")
screen.onkey(go_left, "Left")

# Let's go
reset()
turtle.done()
4

Con rắn di chuyển như thế nào?

Có một số cách để tiếp cận lập trình Trò chơi rắn cổ điển bằng Python (hoặc các ngôn ngữ khác cho vấn đề đó). Thách thức chính là làm thế nào để con rắn di chuyển

Đây là hai cách để khái niệm hóa những gì về cơ bản là cùng một hiệu ứng

    1. Chặt khúc cuối, cho vào phía trước con rắn mỗi khi con rắn "di chuyển"
    1. Tạo một bản sao của phần đầu, thêm nó vào phía trước của con rắn và sau đó cắt bỏ phần cuối cùng

Đây là các bước cho phiên bản thứ hai

Lưu ý Đối với minh họa này, hãy coi mục danh sách ngoài cùng bên trái là đuôi và ngoài cùng bên phải là đầu

  • tạo một mục danh sách mới cho vị trí đầu mới

""" A simple snake game using Turtle Graphics. """
import turtle
import random

WIDTH = 500
HEIGHT = 500
FOOD_SIZE = 10
DELAY = 100  # milliseconds

offsets = {
    "up": (0, 20),
    "down": (0, -20),
    "left": (-20, 0),
    "right": (20, 0)
}

def reset():
    global snake, snake_direction, food_pos, pen
    snake = [[0, 0], [0, 20], [0, 40], [0, 60], [0, 80]]
    snake_direction = "up"
    food_pos = get_random_food_pos()
    food.goto(food_pos)
    # screen.update() Only needed if we are fussed about drawing food before next call to `draw_snake()`.
    move_snake()

def move_snake():
    global snake_direction

    #  Next position for head of snake.
    new_head = snake[-1].copy()
    new_head[0] = snake[-1][0] + offsets[snake_direction][0]
    new_head[1] = snake[-1][1] + offsets[snake_direction][1]

    # Check self-collision
    if new_head in snake[:-1]:  # Or collision with walls?
        reset()
    else:
        # No self-collision so we can continue moving the snake.
        snake.append(new_head)

        # Check food collision
        if not food_collision():
            snake.pop(0)  # Keep the snake the same length unless fed.

        #  Allow screen wrapping
        if snake[-1][0] > WIDTH / 2:
            snake[-1][0] -= WIDTH
        elif snake[-1][0] < - WIDTH / 2:
            snake[-1][0] += WIDTH
        elif snake[-1][1] > HEIGHT / 2:
            snake[-1][1] -= HEIGHT
        elif snake[-1][1] < -HEIGHT / 2:
            snake[-1][1] += HEIGHT

        # Clear previous snake stamps
        pen.clearstamps()

        # Draw snake
        for segment in snake:
            pen.goto(segment[0], segment[1])
            pen.stamp()

        # Refresh screen
        screen.update()

        # Rinse and repeat
        turtle.ontimer(move_snake, DELAY)

def food_collision():
    global food_pos
    if get_distance(snake[-1], food_pos) < 20:
        food_pos = get_random_food_pos()
        food.goto(food_pos)
        return True
    return False

def get_random_food_pos():
    x = random.randint(- WIDTH / 2 + FOOD_SIZE, WIDTH / 2 - FOOD_SIZE)
    y = random.randint(- HEIGHT / 2 + FOOD_SIZE, HEIGHT / 2 - FOOD_SIZE)
    return (x, y)

def get_distance(pos1, pos2):
    x1, y1 = pos1
    x2, y2 = pos2
    distance = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5
    return distance

def go_up():
    global snake_direction
    if snake_direction != "down":
        snake_direction = "up"

def go_right():
    global snake_direction
    if snake_direction != "left":
        snake_direction = "right"

def go_down():
    global snake_direction
    if snake_direction != "up":
        snake_direction = "down"

def go_left():
    global snake_direction
    if snake_direction != "right":
        snake_direction = "left"

# Screen
screen = turtle.Screen()
screen.setup(WIDTH, HEIGHT)
screen.title("Snake")
screen.bgcolor("green")
screen.setup(500, 500)
screen.tracer(0)

# Pen
pen = turtle.Turtle("square")
pen.penup()

# Food
food = turtle.Turtle()
food.shape("circle")
food.color("red")
food.shapesize(FOOD_SIZE / 20)  # Default size of turtle "square" shape is 20.
food.penup()

# Event handlers
screen.listen()
screen.onkey(go_up, "Up")
screen.onkey(go_right, "Right")
screen.onkey(go_down, "Down")
screen.onkey(go_left, "Left")

# Let's go
reset()
turtle.done()
5

Đó là,

new_head = s3

hoặc là

new_head = [40, 0]

  • Tăng tọa độ

    """ A simple snake game using Turtle Graphics. """
    import turtle
    import random
    
    WIDTH = 500
    HEIGHT = 500
    FOOD_SIZE = 10
    DELAY = 100  # milliseconds
    
    offsets = {
        "up": (0, 20),
        "down": (0, -20),
        "left": (-20, 0),
        "right": (20, 0)
    }
    
    def reset():
        global snake, snake_direction, food_pos, pen
        snake = [[0, 0], [0, 20], [0, 40], [0, 60], [0, 80]]
        snake_direction = "up"
        food_pos = get_random_food_pos()
        food.goto(food_pos)
        # screen.update() Only needed if we are fussed about drawing food before next call to `draw_snake()`.
        move_snake()
    
    def move_snake():
        global snake_direction
    
        #  Next position for head of snake.
        new_head = snake[-1].copy()
        new_head[0] = snake[-1][0] + offsets[snake_direction][0]
        new_head[1] = snake[-1][1] + offsets[snake_direction][1]
    
        # Check self-collision
        if new_head in snake[:-1]:  # Or collision with walls?
            reset()
        else:
            # No self-collision so we can continue moving the snake.
            snake.append(new_head)
    
            # Check food collision
            if not food_collision():
                snake.pop(0)  # Keep the snake the same length unless fed.
    
            #  Allow screen wrapping
            if snake[-1][0] > WIDTH / 2:
                snake[-1][0] -= WIDTH
            elif snake[-1][0] < - WIDTH / 2:
                snake[-1][0] += WIDTH
            elif snake[-1][1] > HEIGHT / 2:
                snake[-1][1] -= HEIGHT
            elif snake[-1][1] < -HEIGHT / 2:
                snake[-1][1] += HEIGHT
    
            # Clear previous snake stamps
            pen.clearstamps()
    
            # Draw snake
            for segment in snake:
                pen.goto(segment[0], segment[1])
                pen.stamp()
    
            # Refresh screen
            screen.update()
    
            # Rinse and repeat
            turtle.ontimer(move_snake, DELAY)
    
    def food_collision():
        global food_pos
        if get_distance(snake[-1], food_pos) < 20:
            food_pos = get_random_food_pos()
            food.goto(food_pos)
            return True
        return False
    
    def get_random_food_pos():
        x = random.randint(- WIDTH / 2 + FOOD_SIZE, WIDTH / 2 - FOOD_SIZE)
        y = random.randint(- HEIGHT / 2 + FOOD_SIZE, HEIGHT / 2 - FOOD_SIZE)
        return (x, y)
    
    def get_distance(pos1, pos2):
        x1, y1 = pos1
        x2, y2 = pos2
        distance = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5
        return distance
    
    def go_up():
        global snake_direction
        if snake_direction != "down":
            snake_direction = "up"
    
    def go_right():
        global snake_direction
        if snake_direction != "left":
            snake_direction = "right"
    
    def go_down():
        global snake_direction
        if snake_direction != "up":
            snake_direction = "down"
    
    def go_left():
        global snake_direction
        if snake_direction != "right":
            snake_direction = "left"
    
    # Screen
    screen = turtle.Screen()
    screen.setup(WIDTH, HEIGHT)
    screen.title("Snake")
    screen.bgcolor("green")
    screen.setup(500, 500)
    screen.tracer(0)
    
    # Pen
    pen = turtle.Turtle("square")
    pen.penup()
    
    # Food
    food = turtle.Turtle()
    food.shape("circle")
    food.color("red")
    food.shapesize(FOOD_SIZE / 20)  # Default size of turtle "square" shape is 20.
    food.penup()
    
    # Event handlers
    screen.listen()
    screen.onkey(go_up, "Up")
    screen.onkey(go_right, "Right")
    screen.onkey(go_down, "Down")
    screen.onkey(go_left, "Left")
    
    # Let's go
    reset()
    turtle.done()
    
    6 của
    """ A simple snake game using Turtle Graphics. """
    import turtle
    import random
    
    WIDTH = 500
    HEIGHT = 500
    FOOD_SIZE = 10
    DELAY = 100  # milliseconds
    
    offsets = {
        "up": (0, 20),
        "down": (0, -20),
        "left": (-20, 0),
        "right": (20, 0)
    }
    
    def reset():
        global snake, snake_direction, food_pos, pen
        snake = [[0, 0], [0, 20], [0, 40], [0, 60], [0, 80]]
        snake_direction = "up"
        food_pos = get_random_food_pos()
        food.goto(food_pos)
        # screen.update() Only needed if we are fussed about drawing food before next call to `draw_snake()`.
        move_snake()
    
    def move_snake():
        global snake_direction
    
        #  Next position for head of snake.
        new_head = snake[-1].copy()
        new_head[0] = snake[-1][0] + offsets[snake_direction][0]
        new_head[1] = snake[-1][1] + offsets[snake_direction][1]
    
        # Check self-collision
        if new_head in snake[:-1]:  # Or collision with walls?
            reset()
        else:
            # No self-collision so we can continue moving the snake.
            snake.append(new_head)
    
            # Check food collision
            if not food_collision():
                snake.pop(0)  # Keep the snake the same length unless fed.
    
            #  Allow screen wrapping
            if snake[-1][0] > WIDTH / 2:
                snake[-1][0] -= WIDTH
            elif snake[-1][0] < - WIDTH / 2:
                snake[-1][0] += WIDTH
            elif snake[-1][1] > HEIGHT / 2:
                snake[-1][1] -= HEIGHT
            elif snake[-1][1] < -HEIGHT / 2:
                snake[-1][1] += HEIGHT
    
            # Clear previous snake stamps
            pen.clearstamps()
    
            # Draw snake
            for segment in snake:
                pen.goto(segment[0], segment[1])
                pen.stamp()
    
            # Refresh screen
            screen.update()
    
            # Rinse and repeat
            turtle.ontimer(move_snake, DELAY)
    
    def food_collision():
        global food_pos
        if get_distance(snake[-1], food_pos) < 20:
            food_pos = get_random_food_pos()
            food.goto(food_pos)
            return True
        return False
    
    def get_random_food_pos():
        x = random.randint(- WIDTH / 2 + FOOD_SIZE, WIDTH / 2 - FOOD_SIZE)
        y = random.randint(- HEIGHT / 2 + FOOD_SIZE, HEIGHT / 2 - FOOD_SIZE)
        return (x, y)
    
    def get_distance(pos1, pos2):
        x1, y1 = pos1
        x2, y2 = pos2
        distance = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5
        return distance
    
    def go_up():
        global snake_direction
        if snake_direction != "down":
            snake_direction = "up"
    
    def go_right():
        global snake_direction
        if snake_direction != "left":
            snake_direction = "right"
    
    def go_down():
        global snake_direction
        if snake_direction != "up":
            snake_direction = "down"
    
    def go_left():
        global snake_direction
        if snake_direction != "right":
            snake_direction = "left"
    
    # Screen
    screen = turtle.Screen()
    screen.setup(WIDTH, HEIGHT)
    screen.title("Snake")
    screen.bgcolor("green")
    screen.setup(500, 500)
    screen.tracer(0)
    
    # Pen
    pen = turtle.Turtle("square")
    pen.penup()
    
    # Food
    food = turtle.Turtle()
    food.shape("circle")
    food.color("red")
    food.shapesize(FOOD_SIZE / 20)  # Default size of turtle "square" shape is 20.
    food.penup()
    
    # Event handlers
    screen.listen()
    screen.onkey(go_up, "Up")
    screen.onkey(go_right, "Right")
    screen.onkey(go_down, "Down")
    screen.onkey(go_left, "Left")
    
    # Let's go
    reset()
    turtle.done()
    
    7, cho
    """ A simple snake game using Turtle Graphics. """
    import turtle
    import random
    
    WIDTH = 500
    HEIGHT = 500
    FOOD_SIZE = 10
    DELAY = 100  # milliseconds
    
    offsets = {
        "up": (0, 20),
        "down": (0, -20),
        "left": (-20, 0),
        "right": (20, 0)
    }
    
    def reset():
        global snake, snake_direction, food_pos, pen
        snake = [[0, 0], [0, 20], [0, 40], [0, 60], [0, 80]]
        snake_direction = "up"
        food_pos = get_random_food_pos()
        food.goto(food_pos)
        # screen.update() Only needed if we are fussed about drawing food before next call to `draw_snake()`.
        move_snake()
    
    def move_snake():
        global snake_direction
    
        #  Next position for head of snake.
        new_head = snake[-1].copy()
        new_head[0] = snake[-1][0] + offsets[snake_direction][0]
        new_head[1] = snake[-1][1] + offsets[snake_direction][1]
    
        # Check self-collision
        if new_head in snake[:-1]:  # Or collision with walls?
            reset()
        else:
            # No self-collision so we can continue moving the snake.
            snake.append(new_head)
    
            # Check food collision
            if not food_collision():
                snake.pop(0)  # Keep the snake the same length unless fed.
    
            #  Allow screen wrapping
            if snake[-1][0] > WIDTH / 2:
                snake[-1][0] -= WIDTH
            elif snake[-1][0] < - WIDTH / 2:
                snake[-1][0] += WIDTH
            elif snake[-1][1] > HEIGHT / 2:
                snake[-1][1] -= HEIGHT
            elif snake[-1][1] < -HEIGHT / 2:
                snake[-1][1] += HEIGHT
    
            # Clear previous snake stamps
            pen.clearstamps()
    
            # Draw snake
            for segment in snake:
                pen.goto(segment[0], segment[1])
                pen.stamp()
    
            # Refresh screen
            screen.update()
    
            # Rinse and repeat
            turtle.ontimer(move_snake, DELAY)
    
    def food_collision():
        global food_pos
        if get_distance(snake[-1], food_pos) < 20:
            food_pos = get_random_food_pos()
            food.goto(food_pos)
            return True
        return False
    
    def get_random_food_pos():
        x = random.randint(- WIDTH / 2 + FOOD_SIZE, WIDTH / 2 - FOOD_SIZE)
        y = random.randint(- HEIGHT / 2 + FOOD_SIZE, HEIGHT / 2 - FOOD_SIZE)
        return (x, y)
    
    def get_distance(pos1, pos2):
        x1, y1 = pos1
        x2, y2 = pos2
        distance = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5
        return distance
    
    def go_up():
        global snake_direction
        if snake_direction != "down":
            snake_direction = "up"
    
    def go_right():
        global snake_direction
        if snake_direction != "left":
            snake_direction = "right"
    
    def go_down():
        global snake_direction
        if snake_direction != "up":
            snake_direction = "down"
    
    def go_left():
        global snake_direction
        if snake_direction != "right":
            snake_direction = "left"
    
    # Screen
    screen = turtle.Screen()
    screen.setup(WIDTH, HEIGHT)
    screen.title("Snake")
    screen.bgcolor("green")
    screen.setup(500, 500)
    screen.tracer(0)
    
    # Pen
    pen = turtle.Turtle("square")
    pen.penup()
    
    # Food
    food = turtle.Turtle()
    food.shape("circle")
    food.color("red")
    food.shapesize(FOOD_SIZE / 20)  # Default size of turtle "square" shape is 20.
    food.penup()
    
    # Event handlers
    screen.listen()
    screen.onkey(go_up, "Up")
    screen.onkey(go_right, "Right")
    screen.onkey(go_down, "Down")
    screen.onkey(go_left, "Left")
    
    # Let's go
    reset()
    turtle.done()
    
    8

  • Nối đầu mới cho con rắn

""" A simple snake game using Turtle Graphics. """
import turtle
import random

WIDTH = 500
HEIGHT = 500
FOOD_SIZE = 10
DELAY = 100  # milliseconds

offsets = {
    "up": (0, 20),
    "down": (0, -20),
    "left": (-20, 0),
    "right": (20, 0)
}

def reset():
    global snake, snake_direction, food_pos, pen
    snake = [[0, 0], [0, 20], [0, 40], [0, 60], [0, 80]]
    snake_direction = "up"
    food_pos = get_random_food_pos()
    food.goto(food_pos)
    # screen.update() Only needed if we are fussed about drawing food before next call to `draw_snake()`.
    move_snake()

def move_snake():
    global snake_direction

    #  Next position for head of snake.
    new_head = snake[-1].copy()
    new_head[0] = snake[-1][0] + offsets[snake_direction][0]
    new_head[1] = snake[-1][1] + offsets[snake_direction][1]

    # Check self-collision
    if new_head in snake[:-1]:  # Or collision with walls?
        reset()
    else:
        # No self-collision so we can continue moving the snake.
        snake.append(new_head)

        # Check food collision
        if not food_collision():
            snake.pop(0)  # Keep the snake the same length unless fed.

        #  Allow screen wrapping
        if snake[-1][0] > WIDTH / 2:
            snake[-1][0] -= WIDTH
        elif snake[-1][0] < - WIDTH / 2:
            snake[-1][0] += WIDTH
        elif snake[-1][1] > HEIGHT / 2:
            snake[-1][1] -= HEIGHT
        elif snake[-1][1] < -HEIGHT / 2:
            snake[-1][1] += HEIGHT

        # Clear previous snake stamps
        pen.clearstamps()

        # Draw snake
        for segment in snake:
            pen.goto(segment[0], segment[1])
            pen.stamp()

        # Refresh screen
        screen.update()

        # Rinse and repeat
        turtle.ontimer(move_snake, DELAY)

def food_collision():
    global food_pos
    if get_distance(snake[-1], food_pos) < 20:
        food_pos = get_random_food_pos()
        food.goto(food_pos)
        return True
    return False

def get_random_food_pos():
    x = random.randint(- WIDTH / 2 + FOOD_SIZE, WIDTH / 2 - FOOD_SIZE)
    y = random.randint(- HEIGHT / 2 + FOOD_SIZE, HEIGHT / 2 - FOOD_SIZE)
    return (x, y)

def get_distance(pos1, pos2):
    x1, y1 = pos1
    x2, y2 = pos2
    distance = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5
    return distance

def go_up():
    global snake_direction
    if snake_direction != "down":
        snake_direction = "up"

def go_right():
    global snake_direction
    if snake_direction != "left":
        snake_direction = "right"

def go_down():
    global snake_direction
    if snake_direction != "up":
        snake_direction = "down"

def go_left():
    global snake_direction
    if snake_direction != "right":
        snake_direction = "left"

# Screen
screen = turtle.Screen()
screen.setup(WIDTH, HEIGHT)
screen.title("Snake")
screen.bgcolor("green")
screen.setup(500, 500)
screen.tracer(0)

# Pen
pen = turtle.Turtle("square")
pen.penup()

# Food
food = turtle.Turtle()
food.shape("circle")
food.color("red")
food.shapesize(FOOD_SIZE / 20)  # Default size of turtle "square" shape is 20.
food.penup()

# Event handlers
screen.listen()
screen.onkey(go_up, "Up")
screen.onkey(go_right, "Right")
screen.onkey(go_down, "Down")
screen.onkey(go_left, "Left")

# Let's go
reset()
turtle.done()
0

con rắn = [[0, 0], [20, 0], [40, 0], [60, 0]] ngay bây giờ

hoặc là

con rắn = [s1, s2, s3, H]

  • Cuối cùng, xóa mục ngoài cùng bên trái (
    """ A simple snake game using Turtle Graphics. """
    import turtle
    import random
    
    WIDTH = 500
    HEIGHT = 500
    FOOD_SIZE = 10
    DELAY = 100  # milliseconds
    
    offsets = {
        "up": (0, 20),
        "down": (0, -20),
        "left": (-20, 0),
        "right": (20, 0)
    }
    
    def reset():
        global snake, snake_direction, food_pos, pen
        snake = [[0, 0], [0, 20], [0, 40], [0, 60], [0, 80]]
        snake_direction = "up"
        food_pos = get_random_food_pos()
        food.goto(food_pos)
        # screen.update() Only needed if we are fussed about drawing food before next call to `draw_snake()`.
        move_snake()
    
    def move_snake():
        global snake_direction
    
        #  Next position for head of snake.
        new_head = snake[-1].copy()
        new_head[0] = snake[-1][0] + offsets[snake_direction][0]
        new_head[1] = snake[-1][1] + offsets[snake_direction][1]
    
        # Check self-collision
        if new_head in snake[:-1]:  # Or collision with walls?
            reset()
        else:
            # No self-collision so we can continue moving the snake.
            snake.append(new_head)
    
            # Check food collision
            if not food_collision():
                snake.pop(0)  # Keep the snake the same length unless fed.
    
            #  Allow screen wrapping
            if snake[-1][0] > WIDTH / 2:
                snake[-1][0] -= WIDTH
            elif snake[-1][0] < - WIDTH / 2:
                snake[-1][0] += WIDTH
            elif snake[-1][1] > HEIGHT / 2:
                snake[-1][1] -= HEIGHT
            elif snake[-1][1] < -HEIGHT / 2:
                snake[-1][1] += HEIGHT
    
            # Clear previous snake stamps
            pen.clearstamps()
    
            # Draw snake
            for segment in snake:
                pen.goto(segment[0], segment[1])
                pen.stamp()
    
            # Refresh screen
            screen.update()
    
            # Rinse and repeat
            turtle.ontimer(move_snake, DELAY)
    
    def food_collision():
        global food_pos
        if get_distance(snake[-1], food_pos) < 20:
            food_pos = get_random_food_pos()
            food.goto(food_pos)
            return True
        return False
    
    def get_random_food_pos():
        x = random.randint(- WIDTH / 2 + FOOD_SIZE, WIDTH / 2 - FOOD_SIZE)
        y = random.randint(- HEIGHT / 2 + FOOD_SIZE, HEIGHT / 2 - FOOD_SIZE)
        return (x, y)
    
    def get_distance(pos1, pos2):
        x1, y1 = pos1
        x2, y2 = pos2
        distance = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5
        return distance
    
    def go_up():
        global snake_direction
        if snake_direction != "down":
            snake_direction = "up"
    
    def go_right():
        global snake_direction
        if snake_direction != "left":
            snake_direction = "right"
    
    def go_down():
        global snake_direction
        if snake_direction != "up":
            snake_direction = "down"
    
    def go_left():
        global snake_direction
        if snake_direction != "right":
            snake_direction = "left"
    
    # Screen
    screen = turtle.Screen()
    screen.setup(WIDTH, HEIGHT)
    screen.title("Snake")
    screen.bgcolor("green")
    screen.setup(500, 500)
    screen.tracer(0)
    
    # Pen
    pen = turtle.Turtle("square")
    pen.penup()
    
    # Food
    food = turtle.Turtle()
    food.shape("circle")
    food.color("red")
    food.shapesize(FOOD_SIZE / 20)  # Default size of turtle "square" shape is 20.
    food.penup()
    
    # Event handlers
    screen.listen()
    screen.onkey(go_up, "Up")
    screen.onkey(go_right, "Right")
    screen.onkey(go_down, "Down")
    screen.onkey(go_left, "Left")
    
    # Let's go
    reset()
    turtle.done()
    
    1 hoặc
    """ A simple snake game using Turtle Graphics. """
    import turtle
    import random
    
    WIDTH = 500
    HEIGHT = 500
    FOOD_SIZE = 10
    DELAY = 100  # milliseconds
    
    offsets = {
        "up": (0, 20),
        "down": (0, -20),
        "left": (-20, 0),
        "right": (20, 0)
    }
    
    def reset():
        global snake, snake_direction, food_pos, pen
        snake = [[0, 0], [0, 20], [0, 40], [0, 60], [0, 80]]
        snake_direction = "up"
        food_pos = get_random_food_pos()
        food.goto(food_pos)
        # screen.update() Only needed if we are fussed about drawing food before next call to `draw_snake()`.
        move_snake()
    
    def move_snake():
        global snake_direction
    
        #  Next position for head of snake.
        new_head = snake[-1].copy()
        new_head[0] = snake[-1][0] + offsets[snake_direction][0]
        new_head[1] = snake[-1][1] + offsets[snake_direction][1]
    
        # Check self-collision
        if new_head in snake[:-1]:  # Or collision with walls?
            reset()
        else:
            # No self-collision so we can continue moving the snake.
            snake.append(new_head)
    
            # Check food collision
            if not food_collision():
                snake.pop(0)  # Keep the snake the same length unless fed.
    
            #  Allow screen wrapping
            if snake[-1][0] > WIDTH / 2:
                snake[-1][0] -= WIDTH
            elif snake[-1][0] < - WIDTH / 2:
                snake[-1][0] += WIDTH
            elif snake[-1][1] > HEIGHT / 2:
                snake[-1][1] -= HEIGHT
            elif snake[-1][1] < -HEIGHT / 2:
                snake[-1][1] += HEIGHT
    
            # Clear previous snake stamps
            pen.clearstamps()
    
            # Draw snake
            for segment in snake:
                pen.goto(segment[0], segment[1])
                pen.stamp()
    
            # Refresh screen
            screen.update()
    
            # Rinse and repeat
            turtle.ontimer(move_snake, DELAY)
    
    def food_collision():
        global food_pos
        if get_distance(snake[-1], food_pos) < 20:
            food_pos = get_random_food_pos()
            food.goto(food_pos)
            return True
        return False
    
    def get_random_food_pos():
        x = random.randint(- WIDTH / 2 + FOOD_SIZE, WIDTH / 2 - FOOD_SIZE)
        y = random.randint(- HEIGHT / 2 + FOOD_SIZE, HEIGHT / 2 - FOOD_SIZE)
        return (x, y)
    
    def get_distance(pos1, pos2):
        x1, y1 = pos1
        x2, y2 = pos2
        distance = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5
        return distance
    
    def go_up():
        global snake_direction
        if snake_direction != "down":
            snake_direction = "up"
    
    def go_right():
        global snake_direction
        if snake_direction != "left":
            snake_direction = "right"
    
    def go_down():
        global snake_direction
        if snake_direction != "up":
            snake_direction = "down"
    
    def go_left():
        global snake_direction
        if snake_direction != "right":
            snake_direction = "left"
    
    # Screen
    screen = turtle.Screen()
    screen.setup(WIDTH, HEIGHT)
    screen.title("Snake")
    screen.bgcolor("green")
    screen.setup(500, 500)
    screen.tracer(0)
    
    # Pen
    pen = turtle.Turtle("square")
    pen.penup()
    
    # Food
    food = turtle.Turtle()
    food.shape("circle")
    food.color("red")
    food.shapesize(FOOD_SIZE / 20)  # Default size of turtle "square" shape is 20.
    food.penup()
    
    # Event handlers
    screen.listen()
    screen.onkey(go_up, "Up")
    screen.onkey(go_right, "Right")
    screen.onkey(go_down, "Down")
    screen.onkey(go_left, "Left")
    
    # Let's go
    reset()
    turtle.done()
    
    2), sử dụng
    """ A simple snake game using Turtle Graphics. """
    import turtle
    import random
    
    WIDTH = 500
    HEIGHT = 500
    FOOD_SIZE = 10
    DELAY = 100  # milliseconds
    
    offsets = {
        "up": (0, 20),
        "down": (0, -20),
        "left": (-20, 0),
        "right": (20, 0)
    }
    
    def reset():
        global snake, snake_direction, food_pos, pen
        snake = [[0, 0], [0, 20], [0, 40], [0, 60], [0, 80]]
        snake_direction = "up"
        food_pos = get_random_food_pos()
        food.goto(food_pos)
        # screen.update() Only needed if we are fussed about drawing food before next call to `draw_snake()`.
        move_snake()
    
    def move_snake():
        global snake_direction
    
        #  Next position for head of snake.
        new_head = snake[-1].copy()
        new_head[0] = snake[-1][0] + offsets[snake_direction][0]
        new_head[1] = snake[-1][1] + offsets[snake_direction][1]
    
        # Check self-collision
        if new_head in snake[:-1]:  # Or collision with walls?
            reset()
        else:
            # No self-collision so we can continue moving the snake.
            snake.append(new_head)
    
            # Check food collision
            if not food_collision():
                snake.pop(0)  # Keep the snake the same length unless fed.
    
            #  Allow screen wrapping
            if snake[-1][0] > WIDTH / 2:
                snake[-1][0] -= WIDTH
            elif snake[-1][0] < - WIDTH / 2:
                snake[-1][0] += WIDTH
            elif snake[-1][1] > HEIGHT / 2:
                snake[-1][1] -= HEIGHT
            elif snake[-1][1] < -HEIGHT / 2:
                snake[-1][1] += HEIGHT
    
            # Clear previous snake stamps
            pen.clearstamps()
    
            # Draw snake
            for segment in snake:
                pen.goto(segment[0], segment[1])
                pen.stamp()
    
            # Refresh screen
            screen.update()
    
            # Rinse and repeat
            turtle.ontimer(move_snake, DELAY)
    
    def food_collision():
        global food_pos
        if get_distance(snake[-1], food_pos) < 20:
            food_pos = get_random_food_pos()
            food.goto(food_pos)
            return True
        return False
    
    def get_random_food_pos():
        x = random.randint(- WIDTH / 2 + FOOD_SIZE, WIDTH / 2 - FOOD_SIZE)
        y = random.randint(- HEIGHT / 2 + FOOD_SIZE, HEIGHT / 2 - FOOD_SIZE)
        return (x, y)
    
    def get_distance(pos1, pos2):
        x1, y1 = pos1
        x2, y2 = pos2
        distance = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5
        return distance
    
    def go_up():
        global snake_direction
        if snake_direction != "down":
            snake_direction = "up"
    
    def go_right():
        global snake_direction
        if snake_direction != "left":
            snake_direction = "right"
    
    def go_down():
        global snake_direction
        if snake_direction != "up":
            snake_direction = "down"
    
    def go_left():
        global snake_direction
        if snake_direction != "right":
            snake_direction = "left"
    
    # Screen
    screen = turtle.Screen()
    screen.setup(WIDTH, HEIGHT)
    screen.title("Snake")
    screen.bgcolor("green")
    screen.setup(500, 500)
    screen.tracer(0)
    
    # Pen
    pen = turtle.Turtle("square")
    pen.penup()
    
    # Food
    food = turtle.Turtle()
    food.shape("circle")
    food.color("red")
    food.shapesize(FOOD_SIZE / 20)  # Default size of turtle "square" shape is 20.
    food.penup()
    
    # Event handlers
    screen.listen()
    screen.onkey(go_up, "Up")
    screen.onkey(go_right, "Right")
    screen.onkey(go_down, "Down")
    screen.onkey(go_left, "Left")
    
    # Let's go
    reset()
    turtle.done()
    
    3

Ta đà con rắn đã tiến lên một vị trí

Di chuyển con rắn với đồ họa rùa Python

Chuyển động cơ bản của con rắn có thể được thực hiện trong một chương trình đơn giản như hình dưới đây

import turtle


def move_snake():
    pen.clearstamps()
    new_head = snake[-1].copy()
    new_head[0] += 20
    snake.append(new_head)
    snake.pop(0)
    for segment in snake:
        pen.goto(segment[0], segment[1])
        pen.stamp()
    screen.update()
    turtle.ontimer(move_snake, 200)


snake = [[0, 0], [20, 0], [40, 0]]
screen = turtle.Screen()
screen.tracer(0)
pen = turtle.Turtle("square")
pen.penup()

for segment in snake:
    pen.goto(segment[0], segment[1])
    pen.stamp()
move_snake()

turtle.done()

Để biết thông tin về cách sử dụng hàm

""" A simple snake game using Turtle Graphics. """
import turtle
import random

WIDTH = 500
HEIGHT = 500
FOOD_SIZE = 10
DELAY = 100  # milliseconds

offsets = {
    "up": (0, 20),
    "down": (0, -20),
    "left": (-20, 0),
    "right": (20, 0)
}

def reset():
    global snake, snake_direction, food_pos, pen
    snake = [[0, 0], [0, 20], [0, 40], [0, 60], [0, 80]]
    snake_direction = "up"
    food_pos = get_random_food_pos()
    food.goto(food_pos)
    # screen.update() Only needed if we are fussed about drawing food before next call to `draw_snake()`.
    move_snake()

def move_snake():
    global snake_direction

    #  Next position for head of snake.
    new_head = snake[-1].copy()
    new_head[0] = snake[-1][0] + offsets[snake_direction][0]
    new_head[1] = snake[-1][1] + offsets[snake_direction][1]

    # Check self-collision
    if new_head in snake[:-1]:  # Or collision with walls?
        reset()
    else:
        # No self-collision so we can continue moving the snake.
        snake.append(new_head)

        # Check food collision
        if not food_collision():
            snake.pop(0)  # Keep the snake the same length unless fed.

        #  Allow screen wrapping
        if snake[-1][0] > WIDTH / 2:
            snake[-1][0] -= WIDTH
        elif snake[-1][0] < - WIDTH / 2:
            snake[-1][0] += WIDTH
        elif snake[-1][1] > HEIGHT / 2:
            snake[-1][1] -= HEIGHT
        elif snake[-1][1] < -HEIGHT / 2:
            snake[-1][1] += HEIGHT

        # Clear previous snake stamps
        pen.clearstamps()

        # Draw snake
        for segment in snake:
            pen.goto(segment[0], segment[1])
            pen.stamp()

        # Refresh screen
        screen.update()

        # Rinse and repeat
        turtle.ontimer(move_snake, DELAY)

def food_collision():
    global food_pos
    if get_distance(snake[-1], food_pos) < 20:
        food_pos = get_random_food_pos()
        food.goto(food_pos)
        return True
    return False

def get_random_food_pos():
    x = random.randint(- WIDTH / 2 + FOOD_SIZE, WIDTH / 2 - FOOD_SIZE)
    y = random.randint(- HEIGHT / 2 + FOOD_SIZE, HEIGHT / 2 - FOOD_SIZE)
    return (x, y)

def get_distance(pos1, pos2):
    x1, y1 = pos1
    x2, y2 = pos2
    distance = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5
    return distance

def go_up():
    global snake_direction
    if snake_direction != "down":
        snake_direction = "up"

def go_right():
    global snake_direction
    if snake_direction != "left":
        snake_direction = "right"

def go_down():
    global snake_direction
    if snake_direction != "up":
        snake_direction = "down"

def go_left():
    global snake_direction
    if snake_direction != "right":
        snake_direction = "left"

# Screen
screen = turtle.Screen()
screen.setup(WIDTH, HEIGHT)
screen.title("Snake")
screen.bgcolor("green")
screen.setup(500, 500)
screen.tracer(0)

# Pen
pen = turtle.Turtle("square")
pen.penup()

# Food
food = turtle.Turtle()
food.shape("circle")
food.color("red")
food.shapesize(FOOD_SIZE / 20)  # Default size of turtle "square" shape is 20.
food.penup()

# Event handlers
screen.listen()
screen.onkey(go_up, "Up")
screen.onkey(go_right, "Right")
screen.onkey(go_down, "Down")
screen.onkey(go_left, "Left")

# Let's go
reset()
turtle.done()
4 siêu tiện dụng của Python Turtle Graphics, hãy xem [video của tôi trên Youtube][3]

Danh sách mã trò chơi rắn cổ điển Python

Danh sách cho Trò chơi rắn của chúng tôi ở bên dưới. Tùy thuộc vào mức độ kinh nghiệm của bạn, bạn có thể hiểu chính xác cách thức hoạt động của nó hoặc có thể chỉ một phần nào đó. Tất cả đều ổn

Dù trình độ của bạn là gì, bạn nên thử nghiệm với mã, chơi với nó. Ví dụ: bạn có thể thay đổi một số màu sắc, hoặc tốc độ của con rắn hoặc các điều khiển, v.v.

Đối với những lập trình viên có kinh nghiệm hơn, tại sao không cải thiện ý tưởng cơ bản bằng cách thêm tính năng chấm điểm và các tính năng khác?

Mã hóa vui vẻ,

Robin Andrews

""" A simple snake game using Turtle Graphics. """
import turtle
import random

WIDTH = 500
HEIGHT = 500
FOOD_SIZE = 10
DELAY = 100  # milliseconds

offsets = {
    "up": (0, 20),
    "down": (0, -20),
    "left": (-20, 0),
    "right": (20, 0)
}

def reset():
    global snake, snake_direction, food_pos, pen
    snake = [[0, 0], [0, 20], [0, 40], [0, 60], [0, 80]]
    snake_direction = "up"
    food_pos = get_random_food_pos()
    food.goto(food_pos)
    # screen.update() Only needed if we are fussed about drawing food before next call to `draw_snake()`.
    move_snake()

def move_snake():
    global snake_direction

    #  Next position for head of snake.
    new_head = snake[-1].copy()
    new_head[0] = snake[-1][0] + offsets[snake_direction][0]
    new_head[1] = snake[-1][1] + offsets[snake_direction][1]

    # Check self-collision
    if new_head in snake[:-1]:  # Or collision with walls?
        reset()
    else:
        # No self-collision so we can continue moving the snake.
        snake.append(new_head)

        # Check food collision
        if not food_collision():
            snake.pop(0)  # Keep the snake the same length unless fed.

        #  Allow screen wrapping
        if snake[-1][0] > WIDTH / 2:
            snake[-1][0] -= WIDTH
        elif snake[-1][0] < - WIDTH / 2:
            snake[-1][0] += WIDTH
        elif snake[-1][1] > HEIGHT / 2:
            snake[-1][1] -= HEIGHT
        elif snake[-1][1] < -HEIGHT / 2:
            snake[-1][1] += HEIGHT

        # Clear previous snake stamps
        pen.clearstamps()

        # Draw snake
        for segment in snake:
            pen.goto(segment[0], segment[1])
            pen.stamp()

        # Refresh screen
        screen.update()

        # Rinse and repeat
        turtle.ontimer(move_snake, DELAY)

def food_collision():
    global food_pos
    if get_distance(snake[-1], food_pos) < 20:
        food_pos = get_random_food_pos()
        food.goto(food_pos)
        return True
    return False

def get_random_food_pos():
    x = random.randint(- WIDTH / 2 + FOOD_SIZE, WIDTH / 2 - FOOD_SIZE)
    y = random.randint(- HEIGHT / 2 + FOOD_SIZE, HEIGHT / 2 - FOOD_SIZE)
    return (x, y)

def get_distance(pos1, pos2):
    x1, y1 = pos1
    x2, y2 = pos2
    distance = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5
    return distance

def go_up():
    global snake_direction
    if snake_direction != "down":
        snake_direction = "up"

def go_right():
    global snake_direction
    if snake_direction != "left":
        snake_direction = "right"

def go_down():
    global snake_direction
    if snake_direction != "up":
        snake_direction = "down"

def go_left():
    global snake_direction
    if snake_direction != "right":
        snake_direction = "left"

# Screen
screen = turtle.Screen()
screen.setup(WIDTH, HEIGHT)
screen.title("Snake")
screen.bgcolor("green")
screen.setup(500, 500)
screen.tracer(0)

# Pen
pen = turtle.Turtle("square")
pen.penup()

# Food
food = turtle.Turtle()
food.shape("circle")
food.color("red")
food.shapesize(FOOD_SIZE / 20)  # Default size of turtle "square" shape is 20.
food.penup()

# Event handlers
screen.listen()
screen.onkey(go_up, "Up")
screen.onkey(go_right, "Right")
screen.onkey(go_down, "Down")
screen.onkey(go_left, "Left")

# Let's go
reset()
turtle.done()

For info on using the super-handy `stamp()` function of Python Turtle Graphics, check out [my video on Youtube][3]

### Python Classic Snake Game Code Listing

The listing for our Snake Game is below. Depending on your level of experiece, you may be able to understand exactly how it works or maybe just some of it. That's all fine.

Whatever your level, you should experiment with the code, play with it. For example you could change some colours, or the speed of the snake, or the controls etc.

For more experienced programmers, why not improve upon the basic idea by adding scoring and other features?

    """ A simple snake game using Turtle Graphics. """
    import turtle
    import random
    
    WIDTH = 500
    HEIGHT = 500
    FOOD_SIZE = 10
    DELAY = 100  # milliseconds
    
    offsets = {
        "up": (0, 20),
        "down": (0, -20),
        "left": (-20, 0),
        "right": (20, 0)
    }
    
    def reset():
        global snake, snake_direction, food_pos, pen
        snake = [[0, 0], [0, 20], [0, 40], [0, 50], [0, 60]]
        snake_direction = "up"
        food_pos = get_random_food_pos()
        food.goto(food_pos)
        # screen.update() Only needed if we are fussed about drawing food before next call to `draw_snake()`.
        move_snake()
    
    def move_snake():
        global snake_direction
    
        #  Next position for head of snake.
        new_head = snake[-1].copy()
        new_head[0] = snake[-1][0] + offsets[snake_direction][0]
        new_head[1] = snake[-1][1] + offsets[snake_direction][1]
    
        # Check self-collision
        if new_head in snake[:-1]:  # Or collision with walls?
            reset()
        else:
            # No self-collision so we can continue moving the snake.
            snake.append(new_head)
    
            # Check food collision
            if not food_collision():
                snake.pop(0)  # Keep the snake the same length unless fed.
    
            #  Allow screen wrapping
            if snake[-1][0] > WIDTH / 2:
                snake[-1][0] -= WIDTH
            elif snake[-1][0] < - WIDTH / 2:
                snake[-1][0] += WIDTH
            elif snake[-1][1] > HEIGHT / 2:
                snake[-1][1] -= HEIGHT
            elif snake[-1][1] < -HEIGHT / 2:
                snake[-1][1] += HEIGHT
    
            # Clear previous snake stamps
            pen.clearstamps()
    
            # Draw snake
            for segment in snake:
                pen.goto(segment[0], segment[1])
                pen.stamp()
    
            # Refresh screen
            screen.update()
    
            # Rinse and repeat
            turtle.ontimer(move_snake, DELAY)
    
    def food_collision():
        global food_pos
        if get_distance(snake[-1], food_pos) < 20:
            food_pos = get_random_food_pos()
            food.goto(food_pos)
            return True
        return False
    
    def get_random_food_pos():
        x = random.randint(- WIDTH / 2 + FOOD_SIZE, WIDTH / 2 - FOOD_SIZE)
        y = random.randint(- HEIGHT / 2 + FOOD_SIZE, HEIGHT / 2 - FOOD_SIZE)
        return (x, y)
    
    def get_distance(pos1, pos2):
        x1, y1 = pos1
        x2, y2 = pos2
        distance = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5
        return distance
    
    def go_up():
        global snake_direction
        if snake_direction != "down":
            snake_direction = "up"
    
    def go_right():
        global snake_direction
        if snake_direction != "left":
            snake_direction = "right"
    
    def go_down():
        global snake_direction
        if snake_direction != "up":
            snake_direction = "down"
    
    def go_left():
        global snake_direction
        if snake_direction != "right":
            snake_direction = "left"
    
    # Screen
    screen = turtle.Screen()
    screen.setup(WIDTH, HEIGHT)
    screen.title("Snake")
    screen.bgcolor("green")
    screen.setup(500, 500)
    screen.tracer(0)
    
    # Pen
    pen = turtle.Turtle("square")
    pen.penup()
    
    # Food
    food = turtle.Turtle()
    food.shape("circle")
    food.color("red")
    food.shapesize(FOOD_SIZE / 20)  # Default size of turtle "square" shape is 20.
    food.penup()
    
    # Event handlers
    screen.listen()
    screen.onkey(go_up, "Up")
    screen.onkey(go_right, "Right")
    screen.onkey(go_down, "Down")
    screen.onkey(go_left, "Left")
    
    # Let's go
    reset()
    turtle.done()
    
  *This article is based on a [post][5] on the [Compucademy blog][4]*
  
  Happy coding!

*Robin Andrews*

 [1]: http://compucademy.net/python-turtle-graphics-demos/
 [2]: https://repl.it/@Compucademy/Snake-Game
 [3]: https://www.youtube.com/watch?v=j9Nu08Jtrmw
 [5]: https://compucademy.net/classic-snake-game-with-python-turtle-graphics/
 [4]: https://compucademy.net/blog/

PythonPhát triển trò chơiPython3Gui

Bài báo cáo

Thưởng thức bài viết này?

3

Lệnh rùa Python sao chép và dán

Chia sẻ

Robin Andrews

Chuyên gia giảng dạy Python

Giảng viên Python có trụ sở tại Vương quốc Anh với 15 năm kinh nghiệm giảng dạy. Tôi rất thân thiện và kiên nhẫn, và tôi có thể giải thích những ý tưởng phức tạp theo cách dễ hiểu

con rùa () trong Python là gì?

rùa là thư viện Python được cài đặt sẵn cho phép người dùng tạo ảnh và hình dạng bằng cách cung cấp cho họ một canvas ảo . Cây bút trên màn hình mà bạn sử dụng để vẽ được gọi là con rùa và đây là tên gọi của thư viện.

Làm thế nào để vẽ con rùa bằng Python?

Sử dụng Turtle, chúng ta có thể dễ dàng vẽ trên bảng vẽ. Đầu tiên, chúng tôi nhập mô-đun rùa. Sau đó tạo một cửa sổ, tiếp theo chúng ta tạo đối tượng con rùa và sử dụng phương thức con rùa để vẽ trong bảng vẽ .

Mã rùa là gì?

Nhiều quận và thành phố dọc bờ biển Florida đã thông qua sắc lệnh chiếu sáng rùa biển hạn chế lượng ánh sáng được phép chiếu qua cửa sổ và cửa ra vào . Ánh sáng nhân tạo của công trình ven biển được biết là gây nhầm lẫn cho những con non được dẫn xuống nước bởi ánh sáng của mặt trăng.