Python 贪吃蛇游戏代码示例 - 简单易懂
当然!以下是一个简单的贪吃蛇游戏的 Python 代码示例:
import pygame
import random
# 游戏窗口大小
WINDOW_WIDTH = 640
WINDOW_HEIGHT = 480
GRID_SIZE = 20
GRID_WIDTH = WINDOW_WIDTH // GRID_SIZE
GRID_HEIGHT = WINDOW_HEIGHT // GRID_SIZE
# 颜色定义
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 蛇类
class Snake:
def __init__(self):
self.body = [(GRID_WIDTH // 2, GRID_HEIGHT // 2)]
self.direction = (1, 0)
def move(self):
head = self.body[0]
x = (head[0] + self.direction[0]) % GRID_WIDTH
y = (head[1] + self.direction[1]) % GRID_HEIGHT
new_head = (x, y)
self.body.insert(0, new_head)
self.body.pop()
def change_direction(self, direction):
if (direction[0] * -1, direction[1] * -1) != self.direction:
self.direction = direction
def grow(self):
tail = self.body[-1]
self.body.append(tail)
def check_collision(self):
head = self.body[0]
for segment in self.body[1:]:
if segment == head:
return True
return False
# 食物类
class Food:
def __init__(self):
self.position = (random.randint(0, GRID_WIDTH - 1), random.randint(0, GRID_HEIGHT - 1))
def respawn(self):
self.position = (random.randint(0, GRID_WIDTH - 1), random.randint(0, GRID_HEIGHT - 1))
# 游戏类
class Game:
def __init__(self):
pygame.init()
self.window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
self.clock = pygame.time.Clock()
self.snake = Snake()
self.food = Food()
self.score = 0
def handle_events(self):
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:
self.snake.change_direction((0, -1))
elif event.key == pygame.K_DOWN:
self.snake.change_direction((0, 1))
elif event.key == pygame.K_LEFT:
self.snake.change_direction((-1, 0))
elif event.key == pygame.K_RIGHT:
self.snake.change_direction((1, 0))
def update(self):
self.snake.move()
if self.snake.body[0] == self.food.position:
self.snake.grow()
self.food.respawn()
self.score += 10
if self.snake.check_collision():
self.game_over()
def render(self):
self.window.fill(WHITE)
for segment in self.snake.body:
pygame.draw.rect(self.window, GREEN, (segment[0] * GRID_SIZE, segment[1] * GRID_SIZE, GRID_SIZE, GRID_SIZE))
pygame.draw.rect(self.window, RED, (self.food.position[0] * GRID_SIZE, self.food.position[1] * GRID_SIZE, GRID_SIZE, GRID_SIZE))
pygame.display.set_caption(f'Snake Game (Score: {self.score})')
pygame.display.update()
def game_over(self):
pygame.quit()
quit()
def run(self):
while True:
self.handle_events()
self.update()
self.render()
self.clock.tick(10)
# 启动游戏
game = Game()
game.run()
这个代码使用了 Pygame 库来实现游戏窗口和绘图功能。你可以在运行代码之前确保已经安装了 Pygame 库。
这只是一个简单示例,你可以根据自己的需要对其进行扩展和改进。祝你编写出一个有趣的贪吃蛇游戏!
原文地址: https://www.cveoy.top/t/topic/kIr 著作权归作者所有。请勿转载和采集!