写一个贪吃蛇 python 代码
时间: 2023-08-31 12:43:40 浏览: 97
贪吃蛇python代码
### 回答1:
好的,下面是一个简单的贪吃蛇代码:
```python
import turtle
import time
# 设置画布大小
turtle.setup(width=600, height=600)
# 设置画笔速度
turtle.speed(8)
# 画蛇的身体
def draw_snake(snake_list):
for x, y in snake_list:
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.circle(20)
# 设置蛇头初始位置
head_x = 0
head_y = 0
# 初始化蛇的身体
snake_list = [(head_x, head_y)]
draw_snake(snake_list)
# 设置食物的位置
food_x = 100
food_y = 100
# 画食物
turtle.penup()
turtle.goto(food_x, food_y)
turtle.pendown()
turtle.circle(20)
# 设置移动方向
direction = "right"
# 游戏循环
while True:
# 移动蛇头
if direction == "right":
head_x += 20
elif direction == "left":
head_x -= 20
elif direction == "up":
head_y += 20
elif direction == "down":
head_y -= 20
# 检查是否吃到食物
if head_x == food_x and head_y == food_y:
food_x = turtle.xcor()
food_y = turtle.ycor()
turtle.penup()
turtle.goto(food_x, food_y)
turtle.pendown()
turtle.circle(20)
else:
snake_list.pop(0)
# 在蛇头位置画一个新的圆形
snake_list.append((head_x, head_y))
draw_snake(snake_list)
# 设置方向
turtle.onkeypress(lambda: turtle.setheading(0), "Right")
turtle.onkeypress(lambda: turtle.setheading(180), "Left")
turtle.onkeypress(lambda: turtle.setheading(90), "Up")
turtle.onkeypress(lambda: turtle.setheading(270), "Down")
turtle.listen()
time.sleep(0.1)
```
希望这段代码对您有所帮助!
### 回答2:
这里提供一个简单的贪吃蛇的Python代码:
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
# 定义屏幕尺寸和速度
screen_width = 800
screen_height = 600
snake_size = 20
snake_speed = 10
# 创建屏幕
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("贪吃蛇")
clock = pygame.time.Clock()
font_style = pygame.font.SysFont(None, 50)
score_font = pygame.font.SysFont(None, 35)
# 画出蛇
def draw_snake(snake_size, snake_list):
for x in snake_list:
pygame.draw.rect(screen, BLACK, [x[0], x[1], snake_size, snake_size])
# 显示得分
def show_score(score):
score_text = score_font.render("得分:" + str(score), True, WHITE)
screen.blit(score_text, [0, 0])
# 游戏结束
def game_over():
game_over_text = font_style.render("游戏结束", True, RED)
screen.blit(game_over_text, [screen_width / 6, screen_height / 3])
# 游戏主循环
def game_loop():
game_over_flag = False
game_exit = False
# 初始位置
x1 = screen_width / 2
y1 = screen_height / 2
# 初始速度
x1_change = 0
y1_change = 0
# 蛇的身体
snake_list = []
snake_length = 1
# 随机生成食物位置
food_x = round(random.randrange(0, screen_width - snake_size) / 20.0) * 20.0
food_y = round(random.randrange(0, screen_height - snake_size) / 20.0) * 20.0
while not game_exit:
while game_over_flag == True:
screen.fill(BLACK)
game_over()
show_score(snake_length - 1)
pygame.display.update()
# 重新开始或退出游戏
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_exit = True
game_over_flag = False
if event.key == pygame.K_r:
game_loop()
# 控制蛇的移动
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -snake_size
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_size
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_size
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_size
x1_change = 0
# 判断是否撞到墙壁或自身
if x1 >= screen_width or x1 < 0 or y1 >= screen_height or y1 < 0:
game_over_flag = True
x1 += x1_change
y1 += y1_change
screen.fill(BLACK)
pygame.draw.rect(screen, RED, [food_x, food_y, snake_size, snake_size])
snake_head = []
snake_head.append(x1)
snake_head.append(y1)
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
for x in snake_list[:-1]:
if x == snake_head:
game_over_flag = True
draw_snake(snake_size, snake_list)
show_score(snake_length - 1)
pygame.display.update()
if x1 == food_x and y1 == food_y:
food_x = round(random.randrange(0, screen_width - snake_size) / 20.0) * 20.0
food_y = round(random.randrange(0, screen_height - snake_size) / 20.0) * 20.0
snake_length += 1
clock.tick(snake_speed)
pygame.quit()
quit()
# 运行游戏
game_loop()
```
运行以上代码,就可以在Pygame窗口中玩贪吃蛇游戏。玩家通过方向键控制蛇的移动,吃到食物后蛇长度增加。如果撞到墙壁或自身,则游戏结束,并显示得分。
### 回答3:
贪吃蛇是一款经典的游戏,下面是一个使用Python编写的贪吃蛇代码示例。
```python
import pygame
import random
WIDTH = 800
HEIGHT = 600
FPS = 10
GRIDSIZE = 20
# 定义蛇的类
class Snake(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.body = [(WIDTH / 2, HEIGHT / 2)]
self.direction = random.choice(['up', 'down', 'left', 'right'])
def update(self):
if self.direction == 'up':
new_head = (self.body[0][0], self.body[0][1] - GRIDSIZE)
if self.direction == 'down':
new_head = (self.body[0][0], self.body[0][1] + GRIDSIZE)
if self.direction == 'left':
new_head = (self.body[0][0] - GRIDSIZE, self.body[0][1])
if self.direction == 'right':
new_head = (self.body[0][0] + GRIDSIZE, self.body[0][1])
self.body.insert(0, new_head)
self.body.pop()
def change_direction(self, new_direction):
if new_direction == 'up' and self.direction != 'down':
self.direction = new_direction
if new_direction == 'down' and self.direction != 'up':
self.direction = new_direction
if new_direction == 'left' and self.direction != 'right':
self.direction = new_direction
if new_direction == 'right' and self.direction != 'left':
self.direction = new_direction
def draw(self, screen):
for segment in self.body:
pygame.draw.rect(screen, (0, 255, 0), (segment[0], segment[1], GRIDSIZE, GRIDSIZE))
# 游戏初始化
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("贪吃蛇")
clock = pygame.time.Clock()
snake = Snake()
running = True
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
snake.change_direction('up')
if event.key == pygame.K_DOWN:
snake.change_direction('down')
if event.key == pygame.K_LEFT:
snake.change_direction('left')
if event.key == pygame.K_RIGHT:
snake.change_direction('right')
snake.update()
screen.fill((0, 0, 0))
snake.draw(screen)
pygame.display.flip()
pygame.quit()
```
以上是一个简单的贪吃蛇游戏的Python代码示例。游戏中,蛇会在屏幕上移动,并根据玩家的输入改变方向。
阅读全文