python 贪吃蛇代码
时间: 2023-08-16 14:16:51 浏览: 126
引用\[1\]:在Python中,可以使用Pygame库来编写贪吃蛇游戏的代码。下面是一个简单的贪吃蛇代码示例:
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 定义游戏窗口的大小
window_width = 800
window_height = 600
# 定义蛇的初始位置和大小
snake_x = 100
snake_y = 100
snake_size = 20
# 定义蛇的移动速度
snake_speed = 10
# 定义蛇的移动方向
snake_direction = "right"
# 定义食物的初始位置和大小
food_x = random.randint(0, window_width - snake_size)
food_y = random.randint(0, window_height - snake_size)
food_size = 20
# 创建游戏窗口
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("贪吃蛇游戏")
# 游戏主循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 获取键盘输入,控制蛇的移动方向
keys = pygame.key.get_pressed()
if keys\[pygame.K_UP\] and snake_direction != "down":
snake_direction = "up"
elif keys\[pygame.K_DOWN\] and snake_direction != "up":
snake_direction = "down"
elif keys\[pygame.K_LEFT\] and snake_direction != "right":
snake_direction = "left"
elif keys\[pygame.K_RIGHT\] and snake_direction != "left":
snake_direction = "right"
# 根据蛇的移动方向更新蛇的位置
if snake_direction == "up":
snake_y -= snake_speed
elif snake_direction == "down":
snake_y += snake_speed
elif snake_direction == "left":
snake_x -= snake_speed
elif snake_direction == "right":
snake_x += snake_speed
# 绘制游戏窗口
window.fill((0, 0, 0))
pygame.draw.rect(window, (255, 255, 255), (snake_x, snake_y, snake_size, snake_size))
pygame.draw.rect(window, (255, 0, 0), (food_x, food_y, food_size, food_size))
pygame.display.update()
# 退出游戏
pygame.quit()
```
这段代码使用了Pygame库来创建游戏窗口,并实现了贪吃蛇的基本功能。你可以根据需要进行修改和扩展。希望对你有帮助!\[1\]
#### 引用[.reference_title]
- *1* [Python贪吃蛇 (完整代码+详细注释+粘贴即食)](https://blog.csdn.net/m0_67402235/article/details/125241337)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文