使用Python写一个贪吃蛇小游戏
时间: 2023-06-04 13:04:52 浏览: 97
100行Python代码的贪吃蛇小游戏源码.zip
5星 · 资源好评率100%
好的,我可以帮你解答这个问题。你可以使用Python语言的Pygame库来编写一个简单的贪吃蛇小游戏。下面是基本的代码框架:
```
import pygame
import time
pygame.init()
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 设置屏幕大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('贪吃蛇')
# 设置时钟
clock = pygame.time.Clock()
# 定义方向
direction = 'RIGHT'
# 定义蛇的初始位置和长度
snake_block = 10
snake_speed = 15
x1 = screen_width / 2
y1 = screen_height / 2
x1_change = 0
y1_change = 0
snake_List = []
Length_of_snake = 1
def draw_snake(snake_block, snake_List):
for x in snake_List:
pygame.draw.rect(screen, black, [x[0], x[1], snake_block, snake_block])
# 游戏循环
game_over = False
while not game_over:
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:
direction = 'LEFT'
x1_change = -snake_block
y1_change = 0
elif event.key == pygame.K_RIGHT:
direction = 'RIGHT'
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
direction = 'UP'
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
direction = 'DOWN'
y1_change = snake_block
x1_change = 0
# 判断是否撞墙
if x1 >= screen_width or x1 < 0 or y1 >= screen_height or y1 < 0:
game_over = True
x1 += x1_change
y1 += y1_change
screen.fill(white)
pygame.draw.rect(screen, 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)
pygame.display.update()
# 判断当蛇头吃到食物时
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, screen_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, screen_height - snake_block) / 10.0) * 10.0
Length_of_snake += 1
# 设置游戏帧率和刷新屏幕
clock.tick(snake_speed)
# 退出游戏
pygame.quit()
quit()
```
这只是一个简单的代码框架,你可以根据自己的需要来添加额外的功能或修正代码错误。
阅读全文