贪吃蛇 python代码
时间: 2023-09-08 09:05:13 浏览: 91
snake_Snake!_python_贪吃蛇_
### 回答1:
贪吃蛇是一个经典的游戏,可以用 Python 编写代码实现。这里是一个简单的贪吃蛇游戏的 Python 代码示例:
```
import turtle
import time
# 设置画布大小
turtle.setup(width=600, height=600)
# 创建一个 Turtle 实例
snake = turtle.Turtle()
snake.speed(10)
snake.penup()
# 设置食物的位置
food = turtle.Turtle()
food.speed(0)
food.color("red")
food.penup()
food.goto(0, 100)
food.pendown()
food.begin_fill()
food.circle(10)
food.end_fill()
# 定义蛇的移动方向
directions = ["down", "right", "up", "left"]
# 开始游戏
while True:
snake.forward(20)
# 判断是否吃到食物
if snake.distance(food) < 20:
food.goto(0, 0)
time.sleep(0.2)
turtle.done()
```
希望这个代码示例对你有所帮助。
### 回答2:
贪吃蛇是一种经典的游戏,在Python中可以通过编写一些简单的代码来实现。下面是一个基本的贪吃蛇代码示例:
```
import turtle
import time
import random
delay = 0.1
score = 0
high_score = 0
# 创建窗口
window = turtle.Screen()
window.title("贪吃蛇游戏")
window.bgcolor("black")
window.setup(width=600, height=600)
window.tracer(0)
# 创建蛇头
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("white")
head.penup()
head.goto(0, 0)
head.direction = "Stop"
# 创建食物
food = turtle.Turtle()
food.speed(0)
food.shape("circle")
food.color("red")
food.penup()
food.goto(0, 100)
segments = []
# 计分板
pen = turtle.Turtle()
pen.speed(0)
pen.shape("square")
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 260)
pen.write("得分: 0 最高分: 0", align="center", font=("Courier", 24, "normal"))
# 控制蛇的方向
def go_up():
if head.direction != "down":
head.direction = "up"
def go_down():
if head.direction != "up":
head.direction = "down"
def go_left():
if head.direction != "right":
head.direction = "left"
def go_right():
if head.direction != "left":
head.direction = "right"
def move():
if head.direction == "up":
y = head.ycor()
head.sety(y + 20)
if head.direction == "down":
y = head.ycor()
head.sety(y - 20)
if head.direction == "left":
x = head.xcor()
head.setx(x - 20)
if head.direction == "right":
x = head.xcor()
head.setx(x + 20)
# 键盘绑定
window.listen()
window.onkey(go_up, "w")
window.onkey(go_down, "s")
window.onkey(go_left, "a")
window.onkey(go_right, "d")
# 游戏主循环
while True:
window.update()
# 判断蛇头是否和食物碰到
if head.distance(food) < 20:
# 更新食物的位置
x = random.randint(-280, 280)
y = random.randint(-280, 280)
food.goto(x, y)
# 添加一个身体段
new_segment = turtle.Turtle()
new_segment.speed(0)
new_segment.shape("square")
new_segment.color("grey")
new_segment.penup()
segments.append(new_segment)
# 增加得分
score += 10
if score > high_score:
high_score = score
pen.clear()
pen.write("得分: {} 最高分: {}".format(score, high_score), align="center", font=("Courier", 24, "normal"))
# 更新身体段的位置
for index in range(len(segments) - 1, 0, -1):
x = segments[index - 1].xcor()
y = segments[index - 1].ycor()
segments[index].goto(x, y)
# 更新蛇头的位置
if len(segments) > 0:
x = head.xcor()
y = head.ycor()
segments[0].goto(x, y)
move()
# 判断蛇头是否和身体碰撞
for segment in segments:
if segment.distance(head) < 20:
time.sleep(1)
head.goto(0, 0)
head.direction = "Stop"
for segment in segments:
segment.goto(1000, 1000)
segments.clear()
score = 0
pen.clear()
pen.write("得分: {} 最高分: {}".format(score, high_score), align="center", font=("Courier", 24, "normal"))
time.sleep(delay)
window.mainloop()
```
这段代码使用了Turtle库来创建游戏窗口和游戏中的蛇、食物等元素。通过键盘监听来获取玩家的输入,控制蛇的移动方向。蛇的每一步移动都会检测是否碰到食物或者身体,根据不同情况来更新游戏状态。同时,还有一个计分板记录游戏得分和最高分数。游戏主循环不断重复,以实现动态的游戏画面。
### 回答3:
贪吃蛇游戏是一款非常经典且受欢迎的游戏,下面是一个简单的贪吃蛇python代码:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 创建游戏窗口大小
window_width = 800
window_height = 600
window = pygame.display.set_mode((window_width, window_height))
# 设置颜色(红色、绿色、蓝色)
red = pygame.Color(255, 0, 0)
green = pygame.Color(0, 255, 0)
blue = pygame.Color(0, 0, 255)
# 初始化蛇的坐标
snake_position = [[200, 50], [190, 50], [180, 50]]
fruit_position = [random.randrange(1, (window_width//10)) * 10,
random.randrange(1, (window_height//10)) * 10]
fruit_spawn = True
direction = 'RIGHT'
change_to = direction
score = 0
# 设置游戏帧数
fps = pygame.time.Clock()
# 定义游戏结束函数
def game_over():
my_font = pygame.font.SysFont('times new roman', 90)
game_over_surface = my_font.render('Game Over', True, red)
game_over_rect = game_over_surface.get_rect()
game_over_rect.midtop = (window_width / 2, window_height / 4)
window.fill(blue)
window.blit(game_over_surface, game_over_rect)
pygame.display.flip()
pygame.quit()
quit()
# 定义主函数
while True:
# 控制游戏速度
fps.tick(10)
# 检测用户操作
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT or event.key == ord('d'):
change_to = 'RIGHT'
if event.key == pygame.K_LEFT or event.key == ord('a'):
change_to = 'LEFT'
if event.key == pygame.K_UP or event.key == ord('w'):
change_to = 'UP'
if event.key == pygame.K_DOWN or event.key == ord('s'):
change_to = 'DOWN'
if event.type == pygame.QUIT:
pygame.quit()
quit()
# 防止蛇头与蛇尾相撞
if change_to == 'RIGHT' and not direction == 'LEFT':
direction = 'RIGHT'
if change_to == 'LEFT' and not direction == 'RIGHT':
direction = 'LEFT'
if change_to == 'UP' and not direction == 'DOWN':
direction = 'UP'
if change_to == 'DOWN' and not direction == 'UP':
direction = 'DOWN'
# 根据方向移动蛇的位置
if direction == 'RIGHT':
snake_position[0][0] += 10
if direction == 'LEFT':
snake_position[0][0] -= 10
if direction == 'UP':
snake_position[0][1] -= 10
if direction == 'DOWN':
snake_position[0][1] += 10
# 增加蛇的长度
snake_body = [[snake_position[0][0], snake_position[0][1]]]
if change_to != direction:
snake_position.insert(0, snake_body)
# 检测蛇是否吃掉果实
if snake_position[0][0] == fruit_position[0] and snake_position[0][1] == fruit_position[1]:
score += 1
fruit_spawn = False
else:
snake_position.pop()
if not fruit_spawn:
fruit_position = [random.randrange(1, (window_width//10)) * 10,
random.randrange(1, (window_height//10)) * 10]
fruit_spawn = True
window.fill(blue)
for pos in snake_position:
pygame.draw.rect(window, green,
pygame.Rect(pos[0], pos[1], 10, 10))
pygame.draw.rect(window, red,
pygame.Rect(fruit_position[0], fruit_position[1], 10, 10))
if snake_position[0][0] < 0 or snake_position[0][0] > window_width-10:
game_over()
if snake_position[0][1] < 0 or snake_position[0][1] > window_height-10:
game_over()
for block in snake_position[1:]:
if snake_position[0][0] == block[0] and snake_position[0][1] == block[1]:
game_over()
pygame.display.flip()
# 程序结束
```
阅读全文