基于Python的贪吃蛇代码
以下是一个简单的基于Python的贪吃蛇代码,使用了Pygame库:
import pygame
import random
# 初始化 pygame
pygame.init()
# 定义一些常量
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
BLOCK_SIZE = 10
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 创建一个窗口
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("贪吃蛇")
# 定义蛇的类
class Snake:
def __init__(self):
self.body = [(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)]
self.direction = "right"
def move(self):
x, y = self.body[0]
if self.direction == "up":
y -= BLOCK_SIZE
elif self.direction == "down":
y += BLOCK_SIZE
elif self.direction == "left":
x -= BLOCK_SIZE
elif self.direction == "right":
x += BLOCK_SIZE
self.body.insert(0, (x, y))
self.body.pop()
def turn(self, direction):
self.direction = direction
def draw(self):
for x, y in self.body:
pygame.draw.rect(screen, GREEN, (x, y, BLOCK_SIZE, BLOCK_SIZE))
def grow(self):
x, y = self.body[0]
if self.direction == "up":
y -= BLOCK_SIZE
elif self.direction == "down":
y += BLOCK_SIZE
elif self.direction == "left":
x -= BLOCK_SIZE
elif self.direction == "right":
x += BLOCK_SIZE
self.body.insert(0, (x, y))
def check_collisions(self):
x, y = self.body[0]
if x < 0 or x >= SCREEN_WIDTH or y < 0 or y >= SCREEN_HEIGHT:
return True
for i in range(1, len(self.body)):
if x == self.body[i][0] and y == self.body[i][1]:
return True
return False
# 定义食物的类
class Food:
def __init__(self):
self.x = random.randint(0, SCREEN_WIDTH / BLOCK_SIZE - 1) * BLOCK_SIZE
self.y = random.randint(0, SCREEN_HEIGHT / BLOCK_SIZE - 1) * BLOCK_SIZE
def draw(self):
pygame.draw.rect(screen, RED, (self.x, self.y, BLOCK_SIZE, BLOCK_SIZE))
def check_collision(self, snake):
x, y = snake.body[0]
if self.x == x and self.y == y:
return True
return False
# 创建一个蛇和食物
snake = Snake()
food = Food()
# 游戏循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
snake.turn("up")
elif event.key == pygame.K_DOWN:
snake.turn("down")
elif event.key == pygame.K_LEFT:
snake.turn("left")
elif event.key == pygame.K_RIGHT:
snake.turn("right")
# 移动蛇
snake.move()
# 检查碰撞
if snake.check_collisions():
pygame.quit()
quit()
# 检查是否吃到食物
if food.check_collision(snake):
snake.grow()
food = Food()
# 绘制屏幕
screen.fill(BLACK)
snake.draw()
food.draw()
pygame.display.update()
pygame.time.Clock().tick(20)
以上代码实现了基本的贪吃蛇游戏逻辑,通过键盘控制蛇的移动方向,并在吃到食物时增加蛇的长度。游戏循环中使用了Pygame的事件处理机制,可以方便地处理用户输入事件。
原文地址: https://www.cveoy.top/t/topic/JiW 著作权归作者所有。请勿转载和采集!