Python 贪吃蛇游戏代码示例 - 简单易懂
以下是 Python 语言的贪吃蛇代码示例:
import pygame
import random
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 定义方向
UP = 0
DOWN = 1
LEFT = 2
RIGHT = 3
# 初始化pygame
pygame.init()
# 设置屏幕大小
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('贪吃蛇')
# 定义字体
font = pygame.font.SysFont(None, 30)
# 定义蛇类
class Snake():
def __init__(self):
self.head = [SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2]
self.body = [[self.head[0], self.head[1] + 10],
[self.head[0], self.head[1] + 20],
[self.head[0], self.head[1] + 30]]
self.direction = UP
def move(self):
if self.direction == UP:
self.head[1] -= 10
elif self.direction == DOWN:
self.head[1] += 10
elif self.direction == LEFT:
self.head[0] -= 10
elif self.direction == RIGHT:
self.head[0] += 10
self.body.insert(0, list(self.head))
if self.head == food.food_pos:
food.generate_food()
else:
self.body.pop()
def change_direction(self, direction):
if direction == LEFT and self.direction != RIGHT:
self.direction = LEFT
elif direction == RIGHT and self.direction != LEFT:
self.direction = RIGHT
elif direction == UP and self.direction != DOWN:
self.direction = UP
elif direction == DOWN and self.direction != UP:
self.direction = DOWN
def check_collision(self):
if self.head[0] >= SCREEN_WIDTH or self.head[0] < 0 or self.head[1] >= SCREEN_HEIGHT or self.head[1] < 0:
return True
for block in self.body[1:]:
if self.head == block:
return True
return False
def draw(self, screen):
for block in self.body:
pygame.draw.rect(screen, GREEN, [block[0], block[1], 10, 10])
# 定义食物类
class Food():
def __init__(self):
self.food_pos = [0, 0]
self.generate_food()
def generate_food(self):
self.food_pos = [random.randrange(0, SCREEN_WIDTH // 10) * 10,
random.randrange(0, SCREEN_HEIGHT // 10) * 10]
def draw(self, screen):
pygame.draw.rect(screen, RED, [self.food_pos[0], self.food_pos[1], 10, 10])
# 初始化蛇和食物
snake = Snake()
food = Food()
# 定义游戏循环
clock = pygame.time.Clock()
score = 0
while True:
clock.tick(20)
screen.fill(WHITE)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
snake.change_direction(LEFT)
elif event.key == pygame.K_RIGHT:
snake.change_direction(RIGHT)
elif event.key == pygame.K_UP:
snake.change_direction(UP)
elif event.key == pygame.K_DOWN:
snake.change_direction(DOWN)
snake.move()
if snake.check_collision():
pygame.quit()
quit()
snake.draw(screen)
food.draw(screen)
# 显示得分
text = font.render('Score: ' + str(score), True, BLACK)
screen.blit(text, [0, 0])
# 更新屏幕
pygame.display.update()
# 检查是否吃到食物
if snake.head == food.food_pos:
score += 10
原文地址: https://www.cveoy.top/t/topic/nadA 著作权归作者所有。请勿转载和采集!