使用Turtle模块在Python中创建的贪吃蛇游戏
贪吃蛇是一款街机迷宫游戏,由Gremlin Industries公司制作并在1976年10月由SEGA发布。它被认为是一款优秀的游戏,并在许多代人中越来越受欢迎。贪吃蛇游戏可以通过四个方向按钮来控制贪吃蛇的移动方向。玩这个游戏的目标是通过吃食物或水果来获得最高得分。如果贪吃蛇撞到墙壁或自己,玩家就会失败。
对于初学者来说,想要在Python领域创建一些简单的东西的人可以尝试这个程序。模块Turtle专门设计用于初学者进行玩耍,并提交一个项目的程序。本项目使用的是Python 3.0版本。
因此,我们将创建一个基于Python的游戏, Python 使用以下这些模块。
- Turtle: 这是一个已安装的Python库,允许用户通过提供虚拟画布来绘制图案和图像。
- Time: 它用于计算自事件发生日期以来的秒数。
- Random: 这是一个通过使用random模块在Python中创建随机数的函数。
支持
以下代码可以在使用Sublime Text应用程序的情况下轻松工作,该应用程序专门用于与Python程序一起使用。
另外,也可以使用VSCode来使用这个程序。通过使用VSCode的扩展来安装Python3。然后,将Python3程序保存为你的文件名.py的格式。
以下是使用Turtle模块制作贪吃蛇游戏的逐步方法:
步骤1. 向程序添加模块,然后为每个游戏给出一个初始值。
import turtle as ttl
import time
import random as rdm
delay = 0.1
score = 0
high_score = 0
步骤2: 我们将创建游戏的显示部分,也就是游戏的屏幕,在游戏中我们将创建蛇的头部和蛇在游戏中吃的食物,并在游戏顶部显示分数。
# Here we will creating a window screen
w_n = ttl.Screen()
w_n.title("Snake Game JavaTpoint")
w_n.bgcolor("black")
# The width and height can be put as user's choice
w_n.setup(width = 650, height = 650)
w_n.tracer(0)
# Here, we will create the head of the snake
head1 = ttl.Turtle()
head1.shape("circle")
head1.color("white")
head1.penup()
head1.goto(0, 0)
head1.direction = "Stop"
# Here, we will create the food in the game
food1 = ttl.Turtle()
colors = rdm.choice(['pink', 'yellow', 'blue'])
shapes = rdm.choice(['triangle', 'square', 'circle'])
food1.speed(0)
food1.shape(shapes)
food1.color(colors)
food1.penup()
food1.goto(0, 100)
pen1 = ttl.Turtle()
pen1.speed(0)
pen1.shape("square")
pen1.color("white")
pen1.penup()
pen1.hideturtle()
pen1.goto(0, 250)
pen1.write("Score: 0 High Score: 0", align ="center",
font = ("Consolas", 22, "bold"))
输出:
步骤3: 我们将核实控制蛇移动的键。当我们点击游戏中常用的术语,比如“e”、“s”、“f”和“v”时,我们就能控制蛇在屏幕上移动。
# Here, we will assign the key directions
def group1():
if head1.direction != "down":
head1.direction = "up"
def go_down():
if head1.direction != "up":
head1.direction = "down"
def go_left():
if head1.direction != "right":
head1.direction = "left"
def go_right():
if head1.direction != "left":
head1.direction = "right"
def move1():
if head1.direction == "up":
y1 = head1.ycor()
head1.sety(y1 + 20)
if head1.direction == "down":
y1 = head1.ycor()
head1.sety(y1 - 20)
if head1.direction == "left":
x1 = head1.xcor()
head1.setx(x1 - 20)
if head1.direction == "right":
x1 = head1.xcor()
head1.setx(x1 + 20)
w_n.listen()
w_n.onkeypress(group1, "e")
w_n.onkeypress(go_down, "v")
w_n.onkeypress(go_left, "s")
w_n.onkeypress(go_right, "f")
步骤4: 我们将设计以下游戏内容:
- 蛇吃到水果后身体会变长。
- 给蛇的尾巴上色。
- 当吃到水果时,会记录得分。
- 检查蛇的头部是否与身体或屏幕边缘碰撞。
- 游戏在碰撞后会立即自动重新开始。
- 每次打开窗口时都会展示新的水果设计和形状。
- 分数将被重置为零,并且最高分将保留,直到窗口关闭。
# Code for main gameplay
while True:
w_n.update()
if head1.xcor() > 295 or head1.xcor() < -295 or head1.ycor() > 290 or head1.ycor() < -295:
time.sleep(1)
head1.goto(0, 0)
head1.direction = "Stop"
colors = rdm.choice(['pink', 'blue', 'yellow'])
shapes = rdm.choice(['square', 'circle'])
for segment1 in segments1:
segment1.goto(1050, 1050)
segments1.clear()
score = 0
delay = 0.1
pen1.clear()
pen1.write("Score : {} High Score : {} ".format(
score, high_score), align = "center", font = ("Consoles", 22, "bold"))
if head1.distance(food1) < 20:
x = rdm.randint(-275, 275)
y = rdm.randint(-275, 275)
food1.goto(x, y)
# Here, we are adding segment
new_segment1 = ttl.Turtle()
new_segment1.speed(0)
new_segment1.shape("square")
new_segment1.color("orange") # tail colour
new_segment1.penup()
segments.append(new_segment1)
delay -= 0.001
score += 10
if score > high_score:
high_score = score
pen1.clear()
pen1.write("Score: {} High Score: {} ".format(
score, high_score), align = "center", font = ("Consoles", 22, "bold"))
# Checking for head collisions with body segments
for index in range(len(segments1)-1, 0, -1):
x = segments1[index-1].xcor()
y = segments1[index-1].ycor()
segments1[index].goto(x, y)
if len(segments1) > 0:
x1 = head1.xcor()
y1 = head1.ycor()
segments1[0].goto(x1, y1)
move()
for segment1 in segments1:
if segment1.distance(head1) < 20:
time.sleep(1)
head1.goto(0, 0)
head1.direction = "stop"
colors = rdm.choice(['pink', 'blue', 'yellow'])
shapes = rdm.choice(['square', 'triangle'])
for segment1 in segments1:
segment1.goto(1050, 1050)
segment1.clear()
score = 0
delay = 0.1
pen1.clear()
pen1.write("Score: {} High Score: {} ".format(
score, high_score), align = "center", font = ("Consoles", 22, "bold"))
time.sleep(delay)
w_n.mainloop()
以下是贪吃蛇游戏的完整实现代码
import turtle as ttl
import time
import random as rdm
delay = 0.1
score = 0
high_score = 0
# Here we will be creating a window screen
w_n = ttl.Screen()
w_n.title("Snake Game JavaTpoint")
w_n.bgcolor("black")
# The width and height can be put as user's choice
w_n.setup(width = 650, height = 650)
w_n.tracer(0)
# Here, we will create the head of the snake
head1 = ttl.Turtle()
head1.shape("circle")
head1.color("white")
head1.penup()
head1.goto(0, 0)
head1.direction = "Stop"
# Here, we will create the food in the game
food1 = ttl.Turtle()
colors = rdm.choice(['pink', 'yellow', 'blue'])
shapes = rdm.choice(['triangle', 'square', 'circle'])
food1.speed(0)
food1.shape(shapes)
food1.color(colors)
food1.penup()
food1.goto(0, 100)
pen1 = ttl.Turtle()
pen1.speed(0)
pen1.shape("square")
pen1.color("white")
pen1.penup()
pen1.hideturtle()
pen1.goto(0, 250)
pen1.write("Score: 0, High Score: 0", align = "center",
font = ("Consoles", 22, "bold"))
# Here, we will assign the key directions
def group1():
if head1.direction != "down":
head1.direction = "up"
def go_down():
if head1.direction != "up":
head1.direction = "down"
def go_left():
if head1.direction != "right":
head1.direction = "left"
def go_right():
if head1.direction != "left":
head1.direction = "right"
def move():
if head1.direction == "up":
y1 = head1.ycor()
head1.sety(y1 + 20)
if head1.direction == "down":
y1 = head1.ycor()
head1.sety(y1 - 20)
if head1.direction == "left":
x1 = head1.xcor()
head1.setx(x1 - 20)
if head1.direction == "right":
x1 = head1.xcor()
head1.setx(x1 + 20)
w_n.listen()
w_n.onkeypress(group1, "e")
w_n.onkeypress(go_down, "v")
w_n.onkeypress(go_left, "s")
w_n.onkeypress(go_right, "f")
segments1 = []
# Code for main gameplay
while True:
w_n.update()
if head1.xcor() > 290 or head1.xcor() < -290 or head1.ycor() > 290 or head1.ycor() < -290:
time.sleep(1)
head1.goto(0, 0)
head1.direction = "Stop"
colors = rdm.choice(['pink', 'blue', 'yellow'])
shapes = rdm.choice(['square', 'triangle'])
for segment1 in segments1:
segment1.goto(1050, 1050)
segments1.clear()
score = 0
delay = 0.1
pen1.clear()
pen1.write("Score: {} High Score: {} ".format(
score, high_score), align = "center", font = ("candara", 24, "bold"))
if head1.distance(food1) < 20:
x1 = rdm.randint(-275, 275)
y1 = rdm.randint(-275, 275)
food1.goto(x1, y1)
# Here, we are adding segment
new_segment1 = ttl.Turtle()
new_segment1.speed(0)
new_segment1.shape("square")
new_segment1.color("orange") # tail colour
new_segment1.penup()
segments1.append(new_segment1)
delay -= 0.001
score += 10
if score > high_score:
high_score = score
pen1.clear()
pen1.write("Score : {} High Score : {} ".format(
score, high_score), align = "center", font = ("Consoles", 22, "bold"))
# Checking for head collisions with body segments
for index in range(len(segments1)-1, 0, -1):
x1 = segments1[index - 1].xcor()
y1 = segments1[index - 1].ycor()
segments1[index].goto(x1, y1)
if len(segments1) > 0:
x1 = head1.xcor()
y1 = head1.ycor()
segments1[0].goto(x1, y1)
move()
for segment1 in segments1:
if segment1.distance(head1) < 20:
time.sleep(1)
head1.goto(0, 0)
head1.direction = "stop"
colors = rdm.choice(['pink', 'blue', 'yellow'])
shapes = rdm.choice(['square', 'triangle'])
for segment1 in segments1:
segment1.goto(1050, 1050)
segment1.clear()
score = 0
delay = 0.1
pen1.clear()
pen1.write("Score: {} High Score: {} ".format(
score, high_score), align = "center", font = ("Consoles", 22, "bold"))
time.sleep(delay)
w_n.mainloop()
输出: