python-小游戏-贪吃蛇
需要安装turtle
代码—game-snake.py
from turtle import *
from random import randint
gz = 22
bc = gz * 8
screen = Screen()
screen.bgcolor("darkblue")
food = Turtle()
food.color("red")
food.shape("square")
food.up()
food.speed(0)
food.goto(randint(-bc + gz, bc - gz) // gz * gz, randint(-bc + gz, bc - gz) // gz * gz)
liner = Turtle()
liner.speed(0)
liner.up()
liner.goto(-bc, bc)
liner.color("white")
liner.pensize(5)
liner.down()
for i in range(4):
liner.fd(bc * 2)
liner.rt(90)
liner.ht()
score = 0
judge = Turtle()
judge.speed(0)
judge.up()
judge.goto(0, bc + 20)
judge.color("white")
judge.write("得分:{}".format(score), align="center", font=("Kai", 20, "bold"))
judge.ht()
head = Turtle()
head.speed(0)
head.up()
head.color("cyan")
head.shape("square")
snake = []
snake.append(head)
for i in range(2):
body = head.clone()
body.color("white")
body.goto(head.xcor() + (i + 1) * gz, head.ycor())
snake.append(body)
d = [-1, 0]
def move():
last = snake.pop()
first = snake[0]
first.color("white")
last.goto(first.xcor() + d[0] * gz, first.ycor() + d[1] * gz)
last.color("cyan")
snake.insert(0, last)
if snake[0].xcor() == food.xcor() and snake[0].ycor() == food.ycor():
food.ht()
food.goto(randint(-bc + gz, bc - gz) // gz * gz, randint(-bc + gz, bc - gz) // gz * gz)
food.st()
body = snake[-1].clone()
snake.append(body)
global score
score += 1
judge.clear()
judge.write("得分:{}".format(score), align="center", font=("Kai", 20, "bold"))
if (-bc < snake[0].xcor() < bc) and (-bc < snake[0].ycor() < bc):
screen.ontimer(move, 500) # 只有在边界内时才设置定时器
def up():
global d
if d[1] != -1:
d = [0, 1]
def down():
global d
if d[1] != 1:
d = [0, -1]
def left():
global d
if d[0] != 1:
d = [-1, 0]
def right():
global d
if d[0] != -1:
d = [1, 0]
def restart():
global score, d, snake
# 清除之前的得分和蛇
judge.clear()
for segment in snake:
segment.goto(1000, 1000) # 将蛇移到画面外,以便清除
segment.clear()
snake.clear()
# 重新初始化游戏
score = 0
d = [-1, 0]
judge.write("得分:{}".format(score), align="center", font=("Kai", 20, "bold"))
head.goto(0, 0)
snake.append(head)
for i in range(2):
body = head.clone()
body.color("white")
body.goto(head.xcor() + (i + 1) * gz, head.ycor())
snake.append(body)
move()
screen.onkey(up, "Up")
screen.onkey(down, "Down")
screen.onkey(left, "Left")
screen.onkey(right, "Right")
screen.onkey(restart, "space") # 将 restart 函数绑定到空格键
screen.listen()
move()
done() # 添加此行来保持窗口打开状态
运行代码 game-snake.py