贪吃蛇游戏
'''
@File : 0.py
@Author: BC
@Date : 2023-04-20 17:20
贪吃蛇
'''
import pygame
import random
pygame.init()
window_width = 640
window_height = 480
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("贪吃蛇")
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
snake_x = 0
snake_y = 0
snake_width = 10
snake_height = 10
snake_list = []
snake_length = 1
direction = "right"
food_x = round(random.randrange(0, window_width - snake_width) / 10.0) * 10.0
food_y = round(random.randrange(0, window_height - snake_height) / 10.0) * 10.0
game_over = False
clock = pygame.time.Clock()
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"
elif event.key == pygame.K_RIGHT:
direction = "right"
elif event.key == pygame.K_UP:
direction = "up"
elif event.key == pygame.K_DOWN:
direction = "down"
if snake_x >= window_width or snake_x < 0 or snake_y > window_height or snake_y < 0:
game_over = True
snake_head = []
snake_head.append(snake_x)
snake_head.append(snake_y)
if direction == "right":
snake_x += 10
elif direction == "left":
snake_x -= 10
elif direction == "up":
snake_y -= 10
elif direction == "down":
snake_y += 10
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
window.fill(black)
pygame.draw.rect(window, white, [food_x, food_y, snake_width, snake_height])
for segment in snake_list:
pygame.draw.rect(window, red, [segment[0], segment[1], snake_width, snake_height])
if snake_x == food_x and snake_y == food_y:
food_x = round(random.randrange(0, window_width - snake_width) / 10.0) * 10.0
food_y = round(random.randrange(0, window_height - snake_height) / 10.0) * 10.0
snake_length += 1
pygame.display.update()
clock.tick(15)
pygame.quit()
quit()