鱼C论坛

 找回密码
 立即注册
查看: 1896|回复: 1

[作品展示] 自己写的贪吃蛇

[复制链接]
发表于 2021-2-2 21:04:08 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. import random
  2. import pygame
  3. import sys, os
  4. import easygui as g

  5. msg = "请登录账号(若没有请也在此界面输入)"
  6. title = "请登录账号(若没有请也在此界面输入)"
  7. fieldNames = [" *(新)账号", " *(新)密码", "*再次确认密码"]
  8. fieldValues = []
  9. fieldValues = g.multenterbox(msg, title, fieldNames)

  10. while 1:
  11.     if fieldValues == None:
  12.         break
  13.     errmsg = ""
  14.     for i in range(len(fieldNames)):
  15.         option = fieldNames[i].strip()
  16.         if fieldValues[i].strip() == "" and option[0] == "*":
  17.             errmsg += ('【%s】为必填项。\n\n' % fieldNames[i])
  18.     if errmsg == "":
  19.         break
  20.     fieldValues = g.multenterbox(errmsg, title, fieldNames, fieldValues)


  21. g.msgbox("账号登录(注册)成功\n欢迎进入贪吃蛇!\n游戏十分简易,但后期会持续更新!\n请支持!")
  22. g.msgbox("pythonQQ群:912826718\n点击ok开始游戏!")


  23. def abs_path(rel):
  24.     if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
  25.         # 如果已打包则当前目录是以下路径
  26.         cur_dir = sys._MEIPASS
  27.     else:
  28.         # 如果没有打包,则当前目录是py文件所在目录
  29.         cur_dir = os.path.dirname(os.path.abspath(__file__))
  30.     # 返回文件rel的绝对路径
  31.     return os.path.join(cur_dir, rel)

  32. from pygame.locals import *
  33. pygame.mixer.init()
  34. # 调用 abs_path 函数,读取其他资源文件同理
  35. pygame.mixer.music.load(abs_path("music.mp3"))

  36. snake_speed = 5  # 速度
  37. windows_width = 800
  38. windows_height = 600 #大小
  39. cell_size = 20       #贪方块大小

  40. map_width = int(windows_width / cell_size)
  41. map_height = int(windows_height / cell_size)

  42. # 颜色定义
  43. white = (255, 255, 255)
  44. black = (0, 0, 0)
  45. gray = (230, 230, 230)
  46. dark_gray = (40, 40, 40)
  47. DARKGreen = (0, 155, 0)
  48. Green = (0, 255, 0)
  49. Red = (255, 0, 0)
  50. blue = (0, 0, 255)
  51. dark_blue =(0,0, 139)

  52. BG_COLOR = black #背景色

  53. # 方向
  54. UP = 4
  55. DOWN = 3
  56. LEFT = 2
  57. RIGHT = 1

  58. HEAD = 0 #贪吃蛇

  59. #主函数
  60. def main():
  61.     pygame.init() # 模块初始化
  62.     snake_speed_clock = pygame.time.Clock() # 创建Pygame时钟对象
  63.     screen = pygame.display.set_mode((windows_width, windows_height)) #
  64.     screen.fill(white)

  65.     pygame.display.set_caption("蟒蛇修仙") #设置标题
  66.     show_start_info(screen)               #欢迎信息
  67.     while True:
  68.         running_game(screen, snake_speed_clock)
  69.         show_gameover_info(screen)

  70. #游戏运行主体
  71. def running_game(screen,snake_speed_clock):
  72.     startx = random.randint(3, map_width - 8) #开始位置
  73.     starty = random.randint(3, map_height - 8)
  74.     snake_coords = [{'x': startx, 'y': starty},  #初始贪吃蛇
  75.                   {'x': startx - 1, 'y': starty},
  76.                   {'x': startx - 2, 'y': starty}]

  77.     direction = RIGHT       #  开始时向右移动

  78.     food = get_random_location()     #实物随机位置

  79.     while True:
  80.         for event in pygame.event.get():
  81.             if event.type == QUIT:
  82.                 terminate()
  83.             elif event.type == KEYDOWN:
  84.                 if (event.key == K_LEFT or event.key == K_a) and direction != RIGHT:
  85.                     direction = LEFT
  86.                 elif (event.key == K_RIGHT or event.key == K_d) and direction != LEFT:
  87.                     direction = RIGHT
  88.                 elif (event.key == K_UP or event.key == K_w) and direction != DOWN:
  89.                     direction = UP
  90.                 elif (event.key == K_DOWN or event.key == K_s) and direction != UP:
  91.                     direction = DOWN
  92.                 elif event.key == K_ESCAPE:
  93.                     terminate()

  94.         move_snake(direction, snake_coords) #移动蛇

  95.         ret = snake_is_alive(snake_coords)
  96.         if not ret:
  97.             break # 游戏结束
  98.         snake_is_eat_food(snake_coords, food) #判断蛇是否吃到食物

  99.         screen.fill(BG_COLOR)
  100.         #draw_grid(screen)
  101.         draw_snake(screen, snake_coords)
  102.         draw_food(screen, food)
  103.         draw_score(screen, len(snake_coords) - 3)
  104.         pygame.display.update()
  105.         snake_speed_clock.tick(snake_speed) #控制fps
  106. #将食物画出来
  107. def draw_food(screen, food):
  108.     x = food['x'] * cell_size
  109.     y = food['y'] * cell_size
  110.     appleRect = pygame.Rect(x, y, cell_size, cell_size)
  111.     pygame.draw.rect(screen, Red, appleRect)
  112. #将贪吃蛇画出来
  113. def draw_snake(screen, snake_coords):
  114.     for coord in snake_coords:
  115.         x = coord['x'] * cell_size
  116.         y = coord['y'] * cell_size
  117.         wormSegmentRect = pygame.Rect(x, y, cell_size, cell_size)
  118.         pygame.draw.rect(screen, dark_blue, wormSegmentRect)
  119.         wormInnerSegmentRect = pygame.Rect(                #蛇身子里面的第二层亮绿色
  120.             x + 4, y + 4, cell_size - 8, cell_size - 8)
  121.         pygame.draw.rect(screen, blue, wormInnerSegmentRect)
  122. #画网格(可选)
  123. def draw_grid(screen):
  124.     for x in range(0, windows_width, cell_size):  # draw 水平 lines
  125.         pygame.draw.line(screen, dark_gray, (x, 0), (x, windows_height))
  126.     for y in range(0, windows_height, cell_size):  # draw 垂直 lines
  127.         pygame.draw.line(screen, dark_gray, (0, y), (windows_width, y))
  128. #移动贪吃蛇
  129. def move_snake(direction, snake_coords):
  130.     if direction == UP:
  131.         newHead = {'x': snake_coords[HEAD]['x'], 'y': snake_coords[HEAD]['y'] - 1}
  132.     elif direction == DOWN:
  133.         newHead = {'x': snake_coords[HEAD]['x'], 'y': snake_coords[HEAD]['y'] + 1}
  134.     elif direction == LEFT:
  135.         newHead = {'x': snake_coords[HEAD]['x'] - 1, 'y': snake_coords[HEAD]['y']}
  136.     elif direction == RIGHT:
  137.         newHead = {'x': snake_coords[HEAD]['x'] + 1, 'y': snake_coords[HEAD]['y']}

  138.     snake_coords.insert(0, newHead)
  139. #判断蛇死了没
  140. def snake_is_alive(snake_coords):
  141.     tag = True
  142.     if snake_coords[HEAD]['x'] == -1 or snake_coords[HEAD]['x'] == map_width or snake_coords[HEAD]['y'] == -1 or \
  143.             snake_coords[HEAD]['y'] == map_height:
  144.         tag = False # 蛇碰壁啦
  145.     for snake_body in snake_coords[1:]:
  146.         if snake_body['x'] == snake_coords[HEAD]['x'] and snake_body['y'] == snake_coords[HEAD]['y']:
  147.             tag = False # 蛇碰到自己身体啦
  148.     return tag
  149. #判断贪吃蛇是否吃到食物
  150. def snake_is_eat_food(snake_coords, food):  #如果是列表或字典,那么函数内修改参数内容,就会影响到函数体外的对象。
  151.     if snake_coords[HEAD]['x'] == food['x'] and snake_coords[HEAD]['y'] == food['y']:
  152.         food['x'] = random.randint(0, map_width - 1)
  153.         food['y'] = random.randint(0, map_height - 1) # 实物位置重新设置
  154.     else:
  155.         del snake_coords[-1]  # 如果没有吃到实物, 就向前移动, 那么尾部一格删掉
  156. #食物随机生成
  157. def get_random_location():
  158.     return {'x': random.randint(0, map_width - 1), 'y': random.randint(0, map_height - 1)}
  159. #开始信息显示
  160. def show_start_info(screen):
  161.     if pygame.mixer.music.get_busy() == False:
  162.         pygame.mixer.music.play()
  163.     font = pygame.font.Font('myfont.ttf', 40)
  164.     tip = font.render('按任意键开始游戏', True, (65, 105, 225))
  165.     gamestart = pygame.image.load('ks.png')
  166.     screen.blit(gamestart, (140, 30))
  167.     screen.blit(tip, (240, 550))
  168.     pygame.display.update()

  169.     while True:  #键盘监听事件
  170.         for event in pygame.event.get():  # event handling loop
  171.             if event.type == QUIT:
  172.                 terminate()     #终止程序
  173.             elif event.type == KEYDOWN:
  174.                 if (event.key == K_ESCAPE):  #终止程序
  175.                     terminate() #终止程序
  176.                 else:
  177.                     return #结束此函数, 开始游戏
  178. #游戏结束信息显示
  179. def show_gameover_info(screen):
  180.     if pygame.mixer.music.get_busy() == False:
  181.         pygame.mixer.music.play()
  182.     font = pygame.font.Font('myfont.ttf', 40)
  183.     tip = font.render('按Q或者ESC退出, 按任意键重新开始', True, (65, 105, 225))
  184.     gamestart = pygame.image.load('sw.png')
  185.     screen.blit(gamestart, (60, 0))
  186.     screen.blit(tip, (80, 300))
  187.     pygame.display.update()

  188.     while True:  #键盘监听事件
  189.         for event in pygame.event.get():  # event handling loop
  190.             if event.type == QUIT:
  191.                 terminate()     #终止程序
  192.             elif event.type == KEYDOWN:
  193.                 if event.key == K_ESCAPE or event.key == K_q:  #终止程序
  194.                     terminate() #终止程序
  195.                 else:
  196.                     return #结束此函数, 重新开始游戏
  197. #画成绩
  198. def draw_score(screen,score):
  199.     font = pygame.font.Font('myfont.ttf', 30)
  200.     scoreSurf = font.render('得分: %s' % score, True, Green)
  201.     scoreRect = scoreSurf.get_rect()
  202.     scoreRect.topleft = (windows_width - 120, 10)
  203.     screen.blit(scoreSurf, scoreRect)
  204. #程序终止
  205. def terminate():
  206.     pygame.quit()
  207.     sys.exit()


  208. main()
复制代码


文件保存于同py文件文件夹内
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2021-2-5 14:58:45 From FishC Mobile | 显示全部楼层
真不错
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-28 03:23

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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