如何用python写一个贪吃蛇游戏
时间: 2024-05-06 16:20:06 浏览: 85
以下是一个简单的贪吃蛇游戏实现,使用Python的pygame库:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置游戏屏幕大小
screen_width = 480
screen_height = 480
screen = pygame.display.set_mode((screen_width, screen_height))
# 设置游戏标题
pygame.display.set_caption('贪吃蛇')
# 设置游戏时钟
clock = pygame.time.Clock()
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
# 定义贪吃蛇块的大小
block_size = 10
# 定义字体
font = pygame.font.SysFont(None, 25)
# 定义函数,用于输出文字
def print_text(msg, color, x, y):
text = font.render(msg, True, color)
screen.blit(text, [x, y])
# 定义函数,用于绘制贪吃蛇
def draw_snake(snake_list):
for x,y in snake_list:
pygame.draw.rect(screen, green, [x, y, block_size, block_size])
# 定义主函数
def main():
game_over = False
# 定义贪吃蛇初始位置和长度
snake_x = screen_width / 2
snake_y = screen_height / 2
snake_list = []
snake_length = 1
# 定义食物初始位置
food_x = round(random.randrange(0, screen_width - block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, screen_height - block_size) / 10.0) * 10.0
# 定义贪吃蛇移动的初始方向
direction = 'right'
change_direction = direction
# 游戏循环
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:
change_direction = 'left'
elif event.key == pygame.K_RIGHT:
change_direction = 'right'
elif event.key == pygame.K_UP:
change_direction = 'up'
elif event.key == pygame.K_DOWN:
change_direction = 'down'
# 判断是否改变方向
if change_direction == 'left' and direction != 'right':
direction = 'left'
elif change_direction == 'right' and direction != 'left':
direction = 'right'
elif change_direction == 'up' and direction != 'down':
direction = 'up'
elif change_direction == 'down' and direction != 'up':
direction = 'down'
# 移动贪吃蛇
if direction == 'left':
snake_x -= block_size
elif direction == 'right':
snake_x += block_size
elif direction == 'up':
snake_y -= block_size
elif direction == 'down':
snake_y += block_size
# 判断是否吃到食物
if snake_x == food_x and snake_y == food_y:
food_x = round(random.randrange(0, screen_width - block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, screen_height - block_size) / 10.0) * 10.0
snake_length += 1
# 绘制背景
screen.fill(white)
# 绘制食物
pygame.draw.rect(screen, red, [food_x, food_y, block_size, block_size])
# 绘制贪吃蛇
snake_head = [snake_x, snake_y]
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
for segment in snake_list[:-1]:
if segment == snake_head:
game_over = True
draw_snake(snake_list)
# 输出分数
print_text('Score: ' + str(snake_length - 1), black, 10, 10)
# 更新屏幕
pygame.display.update()
# 设置游戏帧率
clock.tick(10)
# 退出pygame
pygame.quit()
# 调用主函数
if __name__ == '__main__':
main()
```
运行代码后,即可开始游戏。玩家通过方向键控制贪吃蛇的移动,吃到食物分数加1,每撞到自己一次分数减1,当分数小于0时游戏结束。
阅读全文