首先用pip安装前置pygame(这个自行安装)
然后就是调用库,代码都有注释,红的是蛇,白的是分数,用小箭头控制方向
#导入运行库
import pygame
import random
# 初始化游戏
pygame.init()
# 定义游戏界面尺寸
screen_width = 480
screen_height = 480
# 用户登录机制
MAX_LOGIN_ATTEMPTS = 3
login_attempts = 0
logged_in = False
while not logged_in:
username = input("请输入用户名:")
password = input("请输入密码:")
if username == "admin" and password == "admin":
logged_in = True
else:
login_attempts += 1
if login_attempts >= MAX_LOGIN_ATTEMPTS:
print("登录次数超过限制,程序已关闭。")
pygame.quit()
exit()
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 创建游戏窗口
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('贪吃蛇游戏')
# 定义蛇的初始位置和大小
snake_size = 20
snake_x = screen_width // 2
snake_y = screen_height // 2
# 定义蛇的移动速度
snake_speed = 10
snake_x_change = 0
snake_y_change = 0
# 定义食物的初始位置
food_size = 20
food_x = round(random.randrange(0, screen_width - food_size) / 20.0) * 20.0
food_y = round(random.randrange(0, screen_height - food_size) / 20.0) * 20.0
# 定义分数
score = 0
# 定义蛇的身体
snake_body = []
snake_length = 1
clock = pygame.time.Clock()
game_over = False
# 游戏主循环
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and snake_x_change != snake_size:
snake_x_change = -snake_size
snake_y_change = 0
elif event.key == pygame.K_RIGHT and snake_x_change != -snake_size:
snake_x_change = snake_size
snake_y_change = 0
elif event.key == pygame.K_UP and snake_y_change != snake_size:
snake_y_change = -snake_size
snake_x_change = 0
elif event.key == pygame.K_DOWN and snake_y_change != -snake_size:
snake_y_change = snake_size
snake_x_change = 0
# 更新蛇的位置
snake_x += snake_x_change
snake_y += snake_y_change
# 边界判断
if snake_x >= screen_width or snake_x < 0 or snake_y >= screen_height or snake_y < 0:
game_over = True
# 绘制游戏窗口背景
screen.fill(black)
# 绘制食物
pygame.draw.rect(screen, red, [food_x, food_y, food_size, food_size])
# 绘制蛇的身体
snake_head = []
snake_head.append(snake_x)
snake_head.append(snake_y)
snake_body.append(snake_head)
if len(snake_body) > snake_length:
del snake_body[0]
# 检测是否吃到食物
for segment in snake_body[:-1]:
if segment == snake_head:
game_over = True
for x in snake_body:
pygame.draw.rect(screen, white, [x[0], x[1], snake_size, snake_size])
# 更新分数
if snake_x == food_x and snake_y == food_y:
food_x = round(random.randrange(0, screen_width - food_size) / 20.0) * 20.0
food_y = round(random.randrange(0, screen_height - food_size) / 20.0) * 20.0
snake_length += 1
# 更新屏幕
pygame.display.update()
# 控制游戏速度
clock.tick(snake_speed)
#游戏得分
# 游戏结束,退出pygame
pygame.quit()
做了一个用户登录界面,这应该都看的懂吧,账户密码都为admin