本文最后更新于35 天前,其中的信息可能已经过时,如有错误请发送邮件到2847645708@qq.com
万年不更新的我又来更新了,今天闲的无聊的时候写了一段小游戏——贪吃蛇
相信大家一定玩过,没玩过的也不要紧,因为也有可能听过
以下是游戏本体:
import pygame
import random
from collections import deque
#初始化
pygame.init()
WIDTH, HEIGHT = 600, 400
CELL_SUZE = 20
COLS = WIDTH // CELL_SUZE
ROWS = HEIGHT // CELL_SUZE
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("SmartSnake - 按A切换AI模式")
clock = pygame.time.Clock()
#颜色
WHITE = (225, 225, 225)
GREEN = (0, 200, 0)
RED = (200, 0, 0)
BLACK = (0, 0, 0)
DARK_GREEN = (0, 150, 0)
font = pygame.font,SysFont("simhei,", 24)
class SnakeGame:
def __init__(self):
self.reset()
def reset(self):
self.snake = deque([(5, ROWS//2)])
self.direction = (1, 0)
self.food = self.spawn_food()
self.score = 0
self.ai_mode = False
def spawn_food(self):
while True:
pos = (random.randint(0, COLS-1), random.randint(0, ROWS-1))
if pos not in self.snake:
return pos
def move(self, direction=None):
if direction is None:
direction = self.direction
head = self.snake[0]
new_head = (head[0] + direction[0], head[1] + direction[1])
#撞墙检测
if new_head[0] < 0 or new_head[0] >= COLS or new_head[1] < 0 or new_head[1] >= ROWS:
return False
#装自己
if new_head in self.snake:
return False
self.snake.appendleft(new_head)
if new_head == self.food:
self.score += 1
self.food = self.spawn_food()
else:
self.snake.pop()
self.direction = direction
return True
def ai_move(self):
head = self.snake[0]
fx, fy = self.food
#简单寻路:优先往食物方向走,避开障碍
possible_dirs = []
for dx, dy in [(1,0), (0,1), (-1,0), (0,-1)]:
nx, ny = head[0]+dx, head[1]+dy
if 0 <= nx < COLS and 0 <= ny < ROWS and (nx, ny) not in self.snake:
#计算曼哈顿距离
dist = abs(nx-fx) + abs(ny-fy)
possible_dirs.append((dist, (dx, dy)))
if not possible_dirs:
#无路可走,随便动一下(会死)
return self.move(self.direction)
#选最近食物的方向
possible_dirs.sort(key=lambda x: x[0])
best_dir = possible_dirs[0][1]
return self.move(best_dir)
def draw(self):
screen.fill(BLACK)
#画蛇(吾的身体!!!!!!!!)ovo
for i, seg in enumerate(self.snake):
color = GREEN if i != 0 else DARK_GREEN
rect = pygame.Rect(seg[0]*CELL_SUZE, seg[1]*CELL_SIZE, CELL_SIZE, CELL_SIZE)
pygame.draw.rect(screen, RED, rect)
pygame.draw.rect(screen, WHITE, rect, 1)
#画食物(屎)
rect = pygame.Rect(self.food[0]*CELL_SIZE, self.food[1]*CELL_SIZE, CELL_SIZE, CELL_SIZE)
pygame.draw.rect(screen, RED, rect)
pygame.draw.rect(screen, WHITE, rect, 1)
#显示分数和模式
mode_text = "AI" if self.ai_mode else "Manual"
text = font.render(f"Score: {self.score} Mode: {mode_text}", Ture, WHITE)
screen.blit(text, (10, 10))
def main():
game = SnakeGame()
running = True
paused = False
while running:
clock.tick(8) #速度
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
game.ai_move = not game.ai_move
elif event.key == pygame.K_r:
game.reset()
elif event.key == pygame.K_SPACE:
paused = not paused
#手动控制
if not game.ai_mode and not paused:
if event.key == pygame.K_UP and game.direction != (0, 1):
game.direction = (0, -1)
elif event.key == pygame.K_DOWN and game.direction != (0, -1):
game.direction = (0, 1)
elif event.key == pygame.K_LEFT and game.direction != (1, 0):
game.direction = (-1, 0)
elif event.key == pygame.K_RIGHT and game.direction != (-1, 0):
game.direction = (1, 0)
if not paused:
if game.ai_mode:
alive = game.ai_move()
else:
alive = game.move()
if not alive:
print(f"Game Over! Score: {game.score}")
game.reset()
game.draw()
pygame.display.flip()
pygame.quit()
if __name__ == "__main__":
main()
复制粘贴即可,要改可以自己来改哦~
欧克,本篇文章结束~
可以在评论区和我的QQ群来讨论哦~
ps:需要pygame软件包


