给我用python实现贪吃蛇
时间: 2023-12-17 11:04:07 浏览: 87
教你一步步利用python实现贪吃蛇游戏
好的,我可以帮您解决这个问题。以下是一个基本的贪吃蛇游戏的 Python 实现:
```python
import pygame
import random
pygame.init()
# 设置窗口大小和标题
screen_width = 400
screen_height = 400
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("贪吃蛇游戏")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
# 定义蛇的属性
block_size = 10
snake_speed = 15
# 定义字体和分数
font_style = pygame.font.SysFont(None, 30)
# 显示分数
def show_score(score):
score_text = font_style.render("分数:" + str(score), True, white)
screen.blit(score_text, [0, 0])
# 绘制蛇
def draw_snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(screen, green, [x[0], x[1], snake_block, snake_block])
# 主函数
def game_loop():
game_over = False
game_close = False
x1 = screen_width / 2
y1 = screen_height / 2
x1_change = 0
y1_change = 0
snake_list = []
Length_of_snake = 1
foodx = round(random.randrange(0, screen_width - block_size) / 10.0) * 10.0
foody = round(random.randrange(0, screen_height - block_size) / 10.0) * 10.0
# 主游戏循环
while not game_over:
while game_close == True:
screen.fill(black)
message = font_style.render("Game Over!再试一次按Q退出按C", True, white)
screen.blit(message, [screen_width/6, screen_height/3])
show_score(Length_of_snake - 1)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_c:
game_loop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -block_size
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = block_size
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -block_size
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = block_size
x1_change = 0
# 判断是否超出屏幕
if x1 >= screen_width or x1 < 0 or y1 >= screen_height or y1 < 0:
game_close = True
# 更新移动位置
x1 += x1_change
y1 += y1_change
screen.fill(black)
# 绘制食物
pygame.draw.rect(screen, red, [foodx, foody, block_size, block_size])
# 绘制蛇
snake_head = []
snake_head.append(x1)
snake_head.append(y1)
snake_list.append(snake_head)
if len(snake_list) > Length_of_snake:
del snake_list[0]
for x in snake_list[:-1]:
if x == snake_head:
game_close = True
draw_snake(block_size, snake_list)
show_score(Length_of_snake - 1)
pygame.display.update()
# 如果吃到食物,重新生成食物并增加蛇的长度
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, screen_width - block_size) / 10.0) * 10.0
foody = round(random.randrange(0, screen_height - block_size) / 10.0) * 10.0
Length_of_snake += 1
# 控制蛇移动的速度
clock = pygame.time.Clock()
clock.tick(snake_speed)
pygame.quit()
quit()
game_loop()
```
希望能对您有所帮助!
阅读全文