找回密码
 立即注册

扫一扫,访问微社区

QQ登录

只需一步,快速开始

查看: 4797|回复: 10

[代码与实例] 贪吃蛇代码

2

主题

17

帖子

17

积分

贫民

积分
17
QQ
lufu329 发表于 2021-10-2 16:27:35 | 显示全部楼层 |阅读模式
  1. """贪吃蛇"""

  2. import random
  3. import sys
  4. import time
  5. import pygame
  6. from pygame.locals import *
  7. from collecti** import deque

  8. SCREEN_WIDTH = 600      # 屏幕宽度
  9. SCREEN_HEIGHT = 480     # 屏幕高度
  10. SIZE = 20               # 小方格大小
  11. LINE_WIDTH = 1          # 网格线宽度

  12. # 游戏区域的坐标范围
  13. SCOPE_X = (0, SCREEN_WIDTH // SIZE - 1)
  14. SCOPE_Y = (2, SCREEN_HEIGHT // SIZE - 1)

  15. # 食物的分值及颜色
  16. FOOD_STYLE_LIST = [(10, (255, 100, 100)), (20, (100, 255, 100)), (30, (100, 100, 255))]

  17. LIGHT = (100, 100, 100)
  18. DARK = (200, 200, 200)      # 蛇的颜色
  19. BLACK = (0, 0, 0)           # 网格线颜色
  20. RED = (200, 30, 30)         # 红色,GAME OVER 的字体颜色
  21. BGCOLOR = (40, 40, 60)      # 背景色


  22. def print_text(screen, font, x, y, text, fcolor=(255, 255, 255)):
  23.     imgText = font.render(text, True, fcolor)
  24.     screen.blit(imgText, (x, y))


  25. # 初始化蛇
  26. def init_snake():
  27.     snake = deque()
  28.     snake.append((2, SCOPE_Y[0]))
  29.     snake.append((1, SCOPE_Y[0]))
  30.     snake.append((0, SCOPE_Y[0]))
  31.     return snake


  32. def create_food(snake):
  33.     food_x = random.randint(SCOPE_X[0], SCOPE_X[1])
  34.     food_y = random.randint(SCOPE_Y[0], SCOPE_Y[1])
  35.     while (food_x, food_y) in snake:
  36.         # 如果食物出现在蛇身上,则重来
  37.         food_x = random.randint(SCOPE_X[0], SCOPE_X[1])
  38.         food_y = random.randint(SCOPE_Y[0], SCOPE_Y[1])
  39.     return food_x, food_y


  40. def get_food_style():
  41.     return FOOD_STYLE_LIST[random.randint(0, 2)]


  42. def main():
  43.     pygame.init()
  44.     screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
  45.     pygame.display.set_caption('贪吃蛇')

  46.     font1 = pygame.font.SysFont('SimHei', 24)  # 得分的字体
  47.     font2 = pygame.font.Font(None, 72)  # GAME OVER 的字体
  48.     fwidth, fheight = font2.size('GAME OVER')

  49.     # 如果蛇正在向右移动,那么快速点击向下向左,由于程序刷新没那么快,向下事件会被向左覆盖掉,导致蛇后退,直接GAME OVER
  50.     # b 变量就是用于防止这种情况的发生
  51.     b = True

  52.     # 蛇
  53.     snake = init_snake()
  54.     # 食物
  55.     food = create_food(snake)
  56.     food_style = get_food_style()
  57.     # 方向
  58.     pos = (1, 0)

  59.     game_over = True
  60.     start = False       # 是否开始,当start = True,game_over = True 时,才显示 GAME OVER
  61.     score = 0           # 得分
  62.     orispeed = 0.5      # 原始速度
  63.     speed = orispeed
  64.     last_move_time = None
  65.     pause = False       # 暂停

  66.     while True:
  67.         for event in pygame.event.get():
  68.             if event.type == QUIT:
  69.                 sys.exit()
  70.             elif event.type == KEYDOWN:
  71.                 if event.key == K_RETURN:
  72.                     if game_over:
  73.                         start = True
  74.                         game_over = False
  75.                         b = True
  76.                         snake = init_snake()
  77.                         food = create_food(snake)
  78.                         food_style = get_food_style()
  79.                         pos = (1, 0)
  80.                         # 得分
  81.                         score = 0
  82.                         last_move_time = time.time()
  83.                 elif event.key == K_SPACE:
  84.                     if not game_over:
  85.                         pause = not pause
  86.                 elif event.key in (K_w, K_UP):
  87.                     # 这个判断是为了防止蛇向上移时按了向下键,导致直接 GAME OVER
  88.                     if b and not pos[1]:
  89.                         pos = (0, -1)
  90.                         b = False
  91.                 elif event.key in (K_s, K_DOWN):
  92.                     if b and not pos[1]:
  93.                         pos = (0, 1)
  94.                         b = False
  95.                 elif event.key in (K_a, K_LEFT):
  96.                     if b and not pos[0]:
  97.                         pos = (-1, 0)
  98.                         b = False
  99.                 elif event.key in (K_d, K_RIGHT):
  100.                     if b and not pos[0]:
  101.                         pos = (1, 0)
  102.                         b = False

  103.         # 填充背景色
  104.         screen.fill(BGCOLOR)
  105.         # 画网格线 竖线
  106.         for x in range(SIZE, SCREEN_WIDTH, SIZE):
  107.             pygame.draw.line(screen, BLACK, (x, SCOPE_Y[0] * SIZE), (x, SCREEN_HEIGHT), LINE_WIDTH)
  108.         # 画网格线 横线
  109.         for y in range(SCOPE_Y[0] * SIZE, SCREEN_HEIGHT, SIZE):
  110.             pygame.draw.line(screen, BLACK, (0, y), (SCREEN_WIDTH, y), LINE_WIDTH)

  111.         if not game_over:
  112.             curTime = time.time()
  113.             if curTime - last_move_time > speed:
  114.                 if not pause:
  115.                     b = True
  116.                     last_move_time = curTime
  117.                     next_s = (snake[0][0] + pos[0], snake[0][1] + pos[1])
  118.                     if next_s == food:
  119.                         # 吃到了食物
  120.                         snake.appendleft(next_s)
  121.                         score += food_style[0]
  122.                         speed = orispeed - 0.03 * (score // 100)
  123.                         food = create_food(snake)
  124.                         food_style = get_food_style()
  125.                     else:
  126.                         if SCOPE_X[0] <= next_s[0] <= SCOPE_X[1] and SCOPE_Y[0] <= next_s[1] <= SCOPE_Y[1] \
  127.                                 and next_s not in snake:
  128.                             snake.appendleft(next_s)
  129.                             snake.pop()
  130.                         else:
  131.                             game_over = True

  132.         # 画食物
  133.         if not game_over:
  134.             # 避免 GAME OVER 的时候把 GAME OVER 的字给遮住了
  135.             pygame.draw.rect(screen, food_style[1], (food[0] * SIZE, food[1] * SIZE, SIZE, SIZE), 0)

  136.         # 画蛇
  137.         for s in snake:
  138.             pygame.draw.rect(screen, DARK, (s[0] * SIZE + LINE_WIDTH, s[1] * SIZE + LINE_WIDTH,
  139.                                             SIZE - LINE_WIDTH * 2, SIZE - LINE_WIDTH * 2), 0)

  140.         print_text(screen, font1, 30, 7, f'速度: {score//100}')
  141.         print_text(screen, font1, 450, 7, f'得分: {score}')

  142.         if game_over:
  143.             if start:
  144.                 print_text(screen, font2, (SCREEN_WIDTH - fwidth) // 2, (SCREEN_HEIGHT - fheight) // 2, 'GAME OVER', RED)

  145.         pygame.display.update()


  146. if __name__ == '__main__':
  147.     main()
复制代码
更多代码来找我
回复

使用道具 举报

0

主题

2

帖子

2

积分

贫民

积分
2
newstart008 发表于 2022-1-5 16:25:47 | 显示全部楼层
怎么运行不了
回复 支持 反对

使用道具 举报

0

主题

1

帖子

1

积分

贫民

积分
1
xu280647408 发表于 2022-2-26 19:53:27 | 显示全部楼层
怎么运行
回复

使用道具 举报

0

主题

2

帖子

2

积分

贫民

积分
2
wyq247999 发表于 2022-3-4 19:28:31 | 显示全部楼层

怎么运行
回复

使用道具 举报

2

主题

17

帖子

17

积分

贫民

积分
17
QQ
lufu329  楼主| 发表于 2022-3-6 16:24:44 | 显示全部楼层

按回车键
回复 支持 反对

使用道具 举报

2

主题

17

帖子

17

积分

贫民

积分
17
QQ
lufu329  楼主| 发表于 2022-3-6 16:28:04 | 显示全部楼层

按回车键
回复 支持 反对

使用道具 举报

2

主题

17

帖子

17

积分

贫民

积分
17
QQ
lufu329  楼主| 发表于 2022-3-12 15:52:18 | 显示全部楼层

按enter键
回复 支持 反对

使用道具 举报

0

主题

1

帖子

1

积分

贫民

积分
1
vain 发表于 2022-3-16 18:10:11 | 显示全部楼层
运行的时候老是出问题呀
ay
回复 支持 反对

使用道具 举报

0

主题

1

帖子

1

积分

贫民

积分
1
1955185164 发表于 2022-3-21 20:09:55 | 显示全部楼层
语法错误啊
回复 支持 反对

使用道具 举报

2

主题

17

帖子

17

积分

贫民

积分
17
QQ
lufu329  楼主| 发表于 2022-4-10 15:18:21 | 显示全部楼层
vain 发表于 2022-3-16 18:10
运行的时候老是出问题呀
ay

可能是你没有库,你去下载试试
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表