用python写贪吃蛇
时间: 2023-07-18 21:47:52 浏览: 55
好的,下面是一个简单的Python贪吃蛇游戏的代码:
```python
import pygame
import random
# 初始化
pygame.init()
# 窗口大小
window_width = 500
window_height = 500
# 创建窗口
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('贪吃蛇')
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 字体
font = pygame.font.SysFont(None, 25)
# 更新分数
def update_score(score):
score_text = font.render('Score: ' + str(score), True, black)
window.blit(score_text, [0, 0])
# 绘制贪吃蛇
def draw_snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(window, black, [x[0], x[1], snake_block, snake_block])
# 主函数
def game_loop():
# 蛇的初始位置
x1 = window_width/2
y1 = window_height/2
x1_change = 0
y1_change = 0
snake_block = 10
snake_speed = 20
# 食物的初始位置
foodx = round(random.randrange(0, window_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, window_height - snake_block) / 10.0) * 10.0
# 蛇身列表
snake_List = []
Length_of_snake = 1
game_exit = False
game_over = False
# 游戏主循环
while not game_exit:
while game_over == True:
# 游戏结束
window.fill(white)
game_over_text = font.render('Game Over! Press Q-Quit or C-Play Again', True, black)
window.blit(game_over_text, [window_width/6, window_height/3])
update_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_exit = True
game_over = False
if event.key == pygame.K_c:
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_block
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block
x1_change = 0
# 边界碰撞检测
if x1 >= window_width or x1 < 0 or y1 >= window_height or y1 < 0:
game_over = True
# 更新蛇的位置
x1 += x1_change
y1 += y1_change
# 绘制游戏背景
window.fill(white)
# 绘制食物
pygame.draw.rect(window, red, [foodx, foody, snake_block, snake_block])
# 更新蛇身列表
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_over = True
# 绘制贪吃蛇
draw_snake(snake_block, snake_List)
# 更新分数
update_score(Length_of_snake-1)
# 更新游戏窗口
pygame.display.update()
# 食物和蛇头碰撞检测
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, window_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, window_height - snake_block) / 10.0) * 10.0
Length_of_snake += 1
# 控制游戏速度
pygame.time.Clock().tick(snake_speed)
# 退出游戏
pygame.quit()
quit()
# 运行游戏
game_loop()
```
运行代码,即可看到贪吃蛇游戏的窗口。使用方向键控制贪吃蛇的移动,吃到食物得分加一,碰到边界或者自己的身体游戏结束。
阅读全文