用python写一个贪吃蛇
时间: 2023-03-20 17:03:12 浏览: 31
好的,以下是用Python实现贪吃蛇游戏的代码:
```python
import pygame
import random
pygame.init()
# 设置游戏窗口的宽和高
window_width = 500
window_height = 500
# 创建游戏窗口
game_display = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('贪吃蛇游戏')
# 设置游戏界面颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 定义贪吃蛇的大小
snake_block_size = 10
# 设置贪吃蛇移动的速度
snake_speed = 15
# 定义字体
font_style = pygame.font.SysFont(None, 50)
def our_snake(snake_block_size, snake_list):
for x in snake_list:
pygame.draw.rect(game_display, black, [x[0], x[1], snake_block_size, snake_block_size])
def message(msg, color):
mesg = font_style.render(msg, True, color)
game_display.blit(mesg, [window_width/6, window_height/3])
def game_loop():
game_over = False
game_close = False
# 设置初始位置
x1 = window_width / 2
y1 = window_height / 2
# 设置贪吃蛇的移动方向
x1_change = 0
y1_change = 0
# 定义贪吃蛇的长度
snake_List = []
Length_of_snake = 1
# 定义食物的位置
foodx = round(random.randrange(0, window_width - snake_block_size) / 10.0) * 10.0
foody = round(random.randrange(0, window_height - snake_block_size) / 10.0) * 10.0
while not game_over:
while game_close == True:
game_display.fill(white)
message("你输了!按Q退出,按C重新开始", red)
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 = -snake_block_size
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block_size
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block_size
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block_size
x1_change = 0
# 判断贪吃蛇是否撞墙
if x1 >= window_width or x1 < 0 or y1 >= window_height or y1 < 0:
game_close = True
# 更新贪吃蛇的位置
x1 +=