用python实现贪吃蛇游戏
时间: 2023-06-17 20:08:18 浏览: 110
python实现贪吃蛇游戏
好的,下面是一个简单的贪吃蛇游戏的Python实现,希望能帮到你:
```python
import pygame
import random
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 定义常量
WIDTH = 800
HEIGHT = 600
BLOCK_SIZE = 20
# 初始化 Pygame
pygame.init()
# 设置游戏窗口
size = (WIDTH, HEIGHT)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Snake Game")
# 设置时钟
clock = pygame.time.Clock()
# 定义字体
font = pygame.font.SysFont(None, 25)
# 定义函数,用于显示文字
def message_to_screen(msg, color):
screen_text = font.render(msg, True, color)
screen.blit(screen_text, [WIDTH / 2, HEIGHT / 2])
# 定义函数,用于绘制贪吃蛇
def draw_snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(screen, GREEN, [x[0], x[1], snake_block, snake_block])
# 定义函数,用于显示得分
def show_score(score):
score_text = font.render("Score: " + str(score), True, WHITE)
screen.blit(score_text, [0, 0])
# 定义函数,用于显示游戏结束信息
def game_over():
message_to_screen("Game over! Press Q-Quit or C-Play Again", RED)
# 定义函数,用于运行贪吃蛇游戏
def gameLoop():
game_exit = False
game_over_flag = False
# 初始贪吃蛇的位置和长度
lead_x = WIDTH / 2
lead_y = HEIGHT / 2
lead_x_change = 0
lead_y_change = 0
snake_list = []
snake_length = 1
# 初始食物的位置
food_x = round(random.randrange(0, WIDTH - BLOCK_SIZE) / 20.0) * 20.0
food_y = round(random.randrange(0, HEIGHT - BLOCK_SIZE) / 20.0) * 20.0
while not game_exit:
while game_over_flag == True:
game_over()
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_exit = True
game_over_flag = False
if event.key == pygame.K_c:
gameLoop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
lead_x_change = -BLOCK_SIZE
lead_y_change = 0
elif event.key == pygame.K_RIGHT:
lead_x_change = BLOCK_SIZE
lead_y_change = 0
elif event.key == pygame.K_UP:
lead_y_change = -BLOCK_SIZE
lead_x_change = 0
elif event.key == pygame.K_DOWN:
lead_y_change = BLOCK_SIZE
lead_x_change = 0
# 判断贪吃蛇是否撞墙
if lead_x >= WIDTH or lead_x < 0 or lead_y >= HEIGHT or lead_y < 0:
game_over_flag = True
lead_x += lead_x_change
lead_y += lead_y_change
screen.fill(BLACK)
# 绘制食物
pygame.draw.rect(screen, RED, [food_x, food_y, BLOCK_SIZE, BLOCK_SIZE])
# 将贪吃蛇的头部坐标加入到贪吃蛇列表中
snake_head = []
snake_head.append(lead_x)
snake_head.append(lead_y)
snake_list.append(snake_head)
# 如果贪吃蛇的长度超过了设定的长度,就删除贪吃蛇列表中的第一个坐标
if len(snake_list) > snake_length:
del snake_list[0]
# 判断贪吃蛇是否吃到了食物,如果吃到了,则长度加一,重新生成食物
for block in snake_list[:-1]:
if block == snake_head:
game_over_flag = True
draw_snake(BLOCK_SIZE, snake_list)
show_score(snake_length - 1)
pygame.display.update()
if lead_x == food_x and lead_y == food_y:
food_x = round(random.randrange(0, WIDTH - BLOCK_SIZE) / 20.0) * 20.0
food_y = round(random.randrange(0, HEIGHT - BLOCK_SIZE) / 20.0) * 20.0
snake_length += 1
clock.tick(10)
pygame.quit()
quit()
gameLoop()
```
这是一个比较简单的贪吃蛇游戏实现,你可以根据自己的需要进行修改和扩展。
阅读全文