贪吃蛇代码python
时间: 2023-07-09 10:51:13 浏览: 173
以下是一个简单的贪吃蛇代码,使用Python语言实现:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 设置窗口尺寸和标题
width = 500
height = 500
window = pygame.display.set_mode((width, height))
pygame.display.set_caption("贪吃蛇")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 设置游戏参数
snake_block = 10
snake_speed = 15
# 创建蛇
def snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(window, black, [x[0], x[1], snake_block, snake_block])
# 创建游戏循环
def gameLoop():
game_over = False
game_close = False
# 初始蛇位置和长度
x1 = width / 2
y1 = height / 2
x1_change = 0
y1_change = 0
snake_List = []
Length_of_snake = 1
# 食物随机位置
foodx = round(random.randrange(0, width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, height - snake_block) / 10.0) * 10.0
# 游戏循环
while not game_over:
while game_close == True:
window.fill(white)
font_style = pygame.font.SysFont(None, 50)
message = font_style.render("游戏结束,按 Q 退出,按 C 重新开始", True, black)
window.blit(message, [width / 6, height / 3])
# 游戏结束后的操作
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:
gameLoop()
# 控制蛇移动
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
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 >= width or x1 < 0 or y1 >= height or y1 < 0:
game_close = 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_close = True
# 更新蛇的位置
snake(snake_block, snake_List)
pygame.display.update()
# 判断蛇是否吃到食物
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, height - snake_block) / 10.0) * 10.0
Length_of_snake += 1
# 控制游戏速度
clock = pygame.time.Clock()
clock.tick(snake_speed)
# 退出Pygame
pygame.quit()
quit()
# 运行游戏循环
gameLoop()
```
这个代码实现了基本的贪吃蛇功能,包括蛇的移动、碰撞检测、食物的随机生成、长度的增加等。你可以在此基础上进行更多的扩展和优化。
阅读全文