用python写一个贪吃蛇
时间: 2023-04-01 17:03:00 浏览: 105
使用Python写一个贪吃蛇游戏实例代码
很高兴回答你的问题。关于用 Python 写一个贪吃蛇的问题,我可以给出以下代码示例:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 定义游戏窗口大小
window_width = 600
window_height = 400
# 定义贪吃蛇和食物的大小
snake_size = 10
food_size = 10
# 定义贪吃蛇的初始位置和速度
snake_x = window_width / 2
snake_y = window_height / 2
snake_speed = 10
# 定义食物的初始位置
food_x = random.randrange(, window_width - food_size, food_size)
food_y = random.randrange(, window_height - food_size, food_size)
# 创建游戏窗口
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('贪吃蛇')
# 定义颜色
white = (255, 255, 255)
black = (, , )
red = (255, , )
# 定义字体
font = pygame.font.SysFont(None, 25)
# 定义贪吃蛇的初始长度和方向
snake_length = 1
snake_direction = 'right'
snake_list = []
# 游戏循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
# 处理键盘事件
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and snake_direction != 'right':
snake_direction = 'left'
elif event.key == pygame.K_RIGHT and snake_direction != 'left':
snake_direction = 'right'
elif event.key == pygame.K_UP and snake_direction != 'down':
snake_direction = 'up'
elif event.key == pygame.K_DOWN and snake_direction != 'up':
snake_direction = 'down'
# 移动贪吃蛇
if snake_direction == 'right':
snake_x += snake_speed
elif snake_direction == 'left':
snake_x -= snake_speed
elif snake_direction == 'up':
snake_y -= snake_speed
elif snake_direction == 'down':
snake_y += snake_speed
# 判断贪吃蛇是否吃到食物
if snake_x == food_x and snake_y == food_y:
food_x = random.randrange(, window_width - food_size, food_size)
food_y = random.randrange(, window_height - food_size, food_size)
snake_length += 1
# 绘制游戏界面
window.fill(white)
pygame.draw.rect(window, red, [food_x, food_y, food_size, food_size])
snake_head = []
snake_head.append(snake_x)
snake_head.append(snake_y)
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[]
for segment in snake_list[:-1]:
if segment == snake_head:
pygame.quit()
quit()
for segment in snake_list:
pygame.draw.rect(window, black, [segment[], segment[1], snake_size, snake_size])
# 显示分数
score = font.render('Score: ' + str(snake_length - 1), True, black)
window.blit(score, [, ])
# 更新游戏界面
pygame.display.update()
# 控制游戏帧率
pygame.time.Clock().tick(20)
```
希望这个代码示例能够帮助你写出一个简单的贪吃蛇游戏。如果你有任何问题,欢迎随时向我提问。
阅读全文