python实现贪吃蛇(附源码)
【代码】python实现贪吃蛇(附源码)
·
# 导入必要的库
import pygame
import random
# 初始化pygame
pygame.init()
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 设置屏幕大小
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
# 创建屏幕
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("贪吃蛇")
# 定义蛇的初始位置和大小
snake_block_size = 10
snake_speed = 15
snake_list = []
snake_length = 1
snake_x = SCREEN_WIDTH / 2
snake_y = SCREEN_HEIGHT / 2
# 定义食物的初始位置和大小
food_block_size = 10
food_x = round(random.randrange(0, SCREEN_WIDTH - food_block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, SCREEN_HEIGHT - food_block_size) / 10.0) * 10.0
# 定义字体
font_style = pygame.font.SysFont(None, 50)
# 定义分数
score = 0
# 定义游戏结束函数
def game_over():
message = font_style.render("游戏结束", True, RED)
screen.blit(message, [SCREEN_WIDTH / 3, SCREEN_HEIGHT / 3])
pygame.display.update()
pygame.time.delay(2000)
# 游戏循环
game_over_flag = False
while not game_over_flag:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over_flag = True
# 控制蛇的移动
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
snake_x_change = -snake_block_size
snake_y_change = 0
elif event.key == pygame.K_RIGHT:
snake_x_change = snake_block_size
snake_y_change = 0
elif event.key == pygame.K_UP:
snake_y_change = -snake_block_size
snake_x_change = 0
elif event.key == pygame.K_DOWN:
snake_y_change = snake_block_size
snake_x_change = 0
# 控制蛇的移动
snake_x += snake_x_change
snake_y += snake_y_change
# 判断蛇是否吃到食物
if snake_x == food_x and snake_y == food_y:
food_x = round(random.randrange(0, SCREEN_WIDTH - food_block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, SCREEN_HEIGHT - food_block_size) / 10.0) * 10.0
snake_length += 1
score += 10
# 绘制食物
pygame.draw.rect(screen, GREEN, [food_x, food_y, food_block_size, food_block_size])
# 绘制蛇
snake_head = []
snake_head.append(snake_x)
snake_head.append(snake_y)
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
for x in snake_list[:-1]:
if x == snake_head:
game_over_flag = True
for x in snake_list:
pygame.draw.rect(screen, BLUE, [x[0], x[1], snake_block_size, snake_block_size])
# 绘制分数
score_message = font_style.render("分数: " + str(score), True, BLACK)
screen.blit(score_message, [0, 0])
# 更新屏幕
pygame.display.update()
# 判断蛇是否撞墙
if snake_x >= SCREEN_WIDTH or snake_x < 0 or snake_y >= SCREEN_HEIGHT or snake_y < 0:
game_over_flag = True
# 控制游戏速度
pygame.time.delay(snake_speed)
# 结束pygame
pygame.quit()
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
已为社区贡献2条内容
所有评论(0)