话不多说,直接上代码
下面是一个简单的贪吃蛇游戏的Python代码:
# 导入必要的模块
import pygame
import random
# 初始化pygame
pygame.init()
# 定义一些常量
SCREEN_WIDTH = 480
SCREEN_HEIGHT = 480
BLOCK_SIZE = 10
# 定义一些颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# 创建屏幕对象
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("贪吃蛇")
# 定义Snake类和Food类
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 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 draw(self):
for x, y in self.body:
pygame.draw.rect(screen, GREEN, (x, y, BLOCK_SIZE, BLOCK_SIZE))
def collision(self):
x, y = self.body[0]
if x < 0 or x > SCREEN_WIDTH - BLOCK_SIZE or y < 0 or y > SCREEN_HEIGHT - BLOCK_SIZE:
return True
for i in range(1, len(self.body)):
if self.body[0] == self.body[i]:
return True
return False
class Food:
def __init__(self):
self.position = (random.randint(0, SCREEN_WIDTH-BLOCK_SIZE),
random.randint(0, SCREEN_HEIGHT-BLOCK_SIZE))
def draw(self):
pygame.draw.rect(screen, RED, (self.position[0], self.position[1], BLOCK_SIZE, BLOCK_SIZE))
# 创建Snake和Food对象
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 and snake.direction != "down":
snake.direction = "up"
elif event.key == pygame.K_DOWN and snake.direction != "up":
snake.direction = "down"
elif event.key == pygame.K_LEFT and snake.direction != "right":
snake.direction = "left"
elif event.key == pygame.K_RIGHT and snake.direction != "left":
snake.direction = "right"
# 更新游戏
snake.move()
if snake.body[0] == food.position:
snake.grow()
food = Food()
if snake.collision():
break
# 绘制游戏
screen.fill(BLACK)
snake.draw()
food.draw()
pygame.display.update()
# 游戏结束
pygame.quit()
print("Game over!")
这个代码实现了一个基本的贪吃蛇游戏,它包含Snake类和Food类,还有一个游戏循环来处理事件、更新游戏和绘制游戏。如果你想扩展这个程序,你可以添加更多的关卡、难度级别和游戏元素。