贪吃蛇怀旧版Windows版exe程序-python源码
直接上代码
import pygame import random import sys #贪吃蛇-功能完整,可以正常运行和玩游戏,注释详细方便后期功能扩展 # 初始化游戏 pygame.init() ck_width=640 #窗口宽度 ck_height=480 #窗口高度 window = pygame.display.set_mode((ck_width, ck_height)) pygame.display.set_caption("贪吃蛇") snake_speed = 5 # 蛇的速度,可以手动修改 # 绘制蛇 def draw_snake(snake): for pos in snake: pygame.draw.rect(window, (255, 0, 0), pygame.Rect(pos[0], pos[1], 10, 10)) # 绘制食物 def draw_food(food): pygame.draw.rect(window, (0, 255, 0), pygame.Rect(food[0], food[1], 10, 10)) # 获取随机食物位置 def get_random_food(): x = random.randint(0, 31) * 10 y = random.randint(0, 23) * 10 return (x, y) # 碰撞检测 def check_collision(snake): head = snake[0] if head[0] < 0 or head[0] >= ck_width or head[1] < 0 or head[1] >= ck_height: return True for pos in snake[1:]: if pos == head: return True return False # 显示游戏结束界面 def game_over(): window.fill((255, 255, 255)) font = pygame.font.Font('arial.ttf', 36) # 指定字体 text = font.render("Game Over", True, (0, 0, 0)) window.blit(text, (100, 100)) btn_font = pygame.font.Font('arial.ttf', 24) # 指定字体 btn_text = btn_font.render("再来一局", True, (0, 0, 0)) btn_rect = pygame.Rect(130, 150, 80, 30) pygame.draw.rect(window, (0, 255, 0), btn_rect) window.blit(btn_text, (135, 157)) pygame.display.update() waiting = True while waiting: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: mouse_pos = pygame.mouse.get_pos() if btn_rect.collidepoint(mouse_pos): waiting = False # 游戏主循环 while True: snake = [(100, 50), (90, 50), (80, 50)] food = get_random_food() direction = "right" clock = pygame.time.Clock() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_UP and direction != "down": direction = "up" elif event.key == pygame.K_DOWN and direction != "up": direction = "down" elif event.key == pygame.K_LEFT and direction != "right": direction = "left" elif event.key == pygame.K_RIGHT and direction != "left": direction = "right" if direction == "up": snake.insert(0, (snake[0][0], snake[0][1] - 10)) elif direction == "down": snake.insert(0, (snake[0][0], snake[0][1] + 10)) elif direction == "left": snake.insert(0, (snake[0][0] - 10, snake[0][1])) elif direction == "right": snake.insert(0, (snake[0][0] + 10, snake[0][1])) # 判断蛇与食物是否相撞 if snake[0] == food: food = get_random_food() else: snake.pop() # 判断是否碰撞结束 if check_collision(snake): game_over() break window.fill((0, 0, 0)) draw_snake(snake) draw_food(food) pygame.display.update() clock.tick(snake_speed)
亲测可行
备注:字体文件自己从网上随便下载个,替换进去就行了
btn_font = pygame.font.Font('arial.ttf', 24) # 指定字体
版权声明:
作者:admin
链接:http://blog.mryxh.cn/3300.html
文章版权归作者所有,未经允许请勿转载。
THE END