面是一份基础版的贪吃蛇代码,主要展示了游戏的基本逻辑,如界面绘制、蛇的移动、食物的产生等。
import pygame
import random
# 初始化游戏
pygame.init()
width, height = 500, 500
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('贪吃蛇')
clock = pygame.time.Clock()
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
green = (0, 255, 0)
red = (255, 0, 0)
# 定义蛇和食物
block_size = 10
snake_speed = 15
font_style = pygame.font.SysFont(None, 30)
def draw_snake(snake_list):
for x,y in snake_list:
pygame.draw.rect(screen, green, [x, y, block_size, block_size])
def message(msg, color):
message = font_style.render(msg, True, color)
screen.blit(message, [width/6, height/3])
def gameLoop():
game_over = False
game_close = False
x1 = width / 2
y1 = height / 2
x1_change = 0
y1_change = 0
snake_List = []
Length_of_snake = 1
foodx = round(random.randrange(0, width - block_size) / 10.0) * 10.0
foody = round(random.randrange(0, height - block_size) / 10.0) * 10.0
# 游戏主循环
while not game_over:
while game_close == True:
screen.fill(white)
message("你输了!再玩一次按Q,退出按C", red)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
gameLoop()
elif event.key == pygame.K_c:
game_over = True
game_close = False
# 监听事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -block_size
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = block_size
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -block_size
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = block_size
x1_change = 0
# 判断是否出界
if x1 >= width or x1 < 0 or y1 >= height or y1 < 0:
game_close = True
# 更新蛇的坐标
x1 += x1_change
y1 += y1_change
# 清空屏幕
screen.fill(white)
# 绘制食物和蛇
pygame.draw.rect(screen, red, [foodx, foody, block_size, block_size])
snake_Head = []
snake_Head.append(x1)
snake_Head.append(y1)
snake_List.append(snake_Head)
if len(snake_List) > Length_of_snake:
del snake_List[0]
for x in snake_List[:-1]:
if x == snake_Head:
game_close = True
draw_snake(snake_List)
pygame.display.update()
# 判断蛇是否吃到食物
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, width - block_size) / 10.0) * 10.0
foody = round(random.randrange(0, height - block_size) / 10.0) * 10.0
Length_of_snake += 1
clock.tick(snake_speed)
pygame.quit()
quit()
gameLoop()
代码主要分为三部分:初
始化游戏、游戏主循环和游戏结束处理。在游戏主循环中,首先检测用户的输入以改变蛇的运动方向,并根据蛇的坐标更新游戏界面。然后判断蛇是否撞墙或咬到自己以及是否吃到食物,以决定游戏是否结束或者蛇是否增长。最后,游戏结束时提供继续游戏和退出游戏的选项。