找回密码
 注册
搜索
[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
查看: 20237|回复: 2

[技术讨论] python3 控制台简易贪吃蛇

[复制链接]
发表于 2020-12-22 10:45:55 | 显示全部楼层 |阅读模式
本帖最后由 Gin_Q 于 2021-3-5 09:40 编辑
  1. # coding=utf-8
  2. # author Cool_Breeze

  3. import ctypes
  4. import msvcrt
  5. from time import sleep
  6. from os import system
  7. from random import randrange
  8. from collections import deque
  9. from threading import Thread

  10. # 位置信息结构体
  11. class point(ctypes.Structure):
  12.     _fields_ = [('x', ctypes.c_short),
  13.                 ('y', ctypes.c_short)]

  14. def gotoXYPrint(coord, char):
  15.     global MAINHANDLE
  16.     global HEADICON
  17.     global FOODICON
  18.     ctypes.windll.kernel32.SetConsoleCursorPosition(
  19.         MAINHANDLE, coord)
  20.     if char == HEADICON:
  21.         ctypes.windll.kernel32.SetConsoleTextAttribute(
  22.         MAINHANDLE, 14)
  23.     elif char == FOODICON:
  24.         ctypes.windll.kernel32.SetConsoleTextAttribute(
  25.         MAINHANDLE, 12)
  26.     else:
  27.         ctypes.windll.kernel32.SetConsoleTextAttribute(
  28.         MAINHANDLE, 11)
  29.     print(char, end='', flush=True)


  30. # 边框
  31. def side():
  32.     for n in range(WIDTH-1):
  33.         gotoXYPrint(point(n,0), '+')
  34.         gotoXYPrint(point(n,HIGHT-1), '+')
  35.     for n in range(HIGHT-1):
  36.         gotoXYPrint(point(0,n), '+')
  37.         gotoXYPrint(point(WIDTH-1,n), '+')

  38. def createFood():
  39.     global SNAKE
  40.     global FOODPOINT
  41.     off = False
  42.     while True:
  43.         x = randrange(1, WIDTH-1)
  44.         y = randrange(1, HIGHT-1)
  45.         for n in SNAKE:
  46.             if n.x == x and n.y == y:
  47.                 continue
  48.             else:
  49.                 FOODPOINT.x = x
  50.                 FOODPOINT.y = y
  51.                 gotoXYPrint(FOODPOINT, FOODICON)
  52.                 off = True
  53.         if off: break

  54. def createSnake():
  55.     global SNAKE
  56.     x, y = WIDTH//2, HIGHT//2
  57.     for n in range(3):
  58.         t = point(x+n, y)
  59.         SNAKE.append(t)
  60.         gotoXYPrint(t, HEADICON)

  61. def update():
  62.     for i in SNAKE:
  63.         gotoXYPrint(i, HEADICON)

  64. def _exit(info):
  65.     input(info)
  66.     exit()
  67.      
  68. def collision():
  69.     global SNAKE
  70.     head = SNAKE[0]
  71.     count = 0
  72.     for n in SNAKE:
  73.         count += 1
  74.         if count == 1: continue
  75.         if n.x == head.x and n.y == head.y:
  76.             _exit('游戏结束!')
  77.             
  78.     if head.x == 0 or head.y == 0 or \
  79.        head.x == WIDTH-1 or head.y == HIGHT-1:
  80.        _exit('游戏结束!')

  81. def moveSnake():
  82.     '''
  83.     K == ←
  84.     M == →
  85.     H == ↑
  86.     P == ↓
  87.     '''
  88.     global DIRECTION
  89.     global SNAKE
  90.     global FOODPOINT
  91.      
  92.     if DIRECTION == 'K':
  93.         SNAKE.appendleft(point(SNAKE[0].x-1, SNAKE[0].y))
  94.     elif DIRECTION == 'M':
  95.         SNAKE.appendleft(point(SNAKE[0].x+1, SNAKE[0].y))
  96.     elif DIRECTION == 'H':
  97.         SNAKE.appendleft(point(SNAKE[0].x, SNAKE[0].y-1))
  98.     elif DIRECTION == 'P':
  99.         SNAKE.appendleft(point(SNAKE[0].x, SNAKE[0].y+1))
  100.     # 其他按键不做任何动作
  101.     else: return None
  102.     collision()
  103.     # 是否吃到食物
  104.     if SNAKE[0].x != FOODPOINT.x or SNAKE[0].y != FOODPOINT.y:
  105.         gotoXYPrint(SNAKE.pop(), ' ')
  106.     else:
  107.         createFood()
  108.      
  109.     update()
  110.      
  111. # 长按加速
  112. def Speed():
  113.     global SPEED
  114.     global ORDKEY
  115.     global DIRECTION
  116.      
  117.     while True:
  118.         sleep(0.001)
  119.         if msvcrt.kbhit():
  120.             inputKey = msvcrt.getwch()
  121.             # 特殊按键
  122.             if inputKey == '\000' or inputKey == '\xe0':
  123.                 inputKey = msvcrt.getwch()
  124.                 if DIRECTION == 'K' and inputKey == 'M': continue
  125.                 elif DIRECTION == 'M' and inputKey == 'K': continue
  126.                 elif DIRECTION == 'H' and inputKey == 'P': continue
  127.                 elif DIRECTION == 'P' and inputKey == 'H': continue
  128.             if DIRECTION == inputKey:
  129.                 if SPEED >= 0.02:
  130.                     SPEED -= 0.02
  131.             else:
  132.                 DIRECTION = inputKey
  133.                 SPEED = 0.1

  134. HIGHT = 26
  135. WIDTH = 60
  136. MAINHANDLE = ctypes.windll.kernel32.GetStdHandle(-11)
  137. SNAKE = deque([])
  138. HEADICON = 'O'
  139. FOODICON = '$'
  140. FOODPOINT = point()

  141. DIRECTION = 'K'

  142. system(f'mode con cols={WIDTH} lines={HIGHT}')
  143. system("title 贪吃蛇游戏")
  144. # 隐藏光标
  145. ctypes.windll.kernel32.SetConsoleCursorInfo(
  146.     MAINHANDLE, ctypes.byref(point(1,0)))
  147.      
  148. SPEED = 0.1
  149. ORDKEY = None
  150. def main():
  151.     global DIRECTION
  152.     global SPEED
  153.     side()
  154.     createSnake()
  155.     createFood()
  156.     InputThead = Thread(target=Speed, daemon=True)
  157.     InputThead.start()
  158.     while True:
  159.         moveSnake()
  160.         sleep(SPEED)


  161. if __name__ == '__main__':
  162.     main()
复制代码

评分

参与人数 1技术 +1 收起 理由
slimay + 1 赞一个

查看全部评分

发表于 2021-3-5 14:34:43 | 显示全部楼层
嗯,这个蛇挺苗条

  1. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  2. +                                                          +
  3. +                                                          +
  4. +                                                          +
  5. +                                                          +
  6. +                                                          +
  7. +                                                          +
  8. +                                                          +
  9. +                                                          +
  10. +                                                          +
  11. +                                                          +
  12. +                                                          +
  13. +                                                          +
  14. +                                                          +
  15. +                                                          +
  16. +                                                          +
  17. +                                                          +
  18. +                                                          +
  19. +                                o                        +
  20. +                                o                        +
  21. +                                □                        +
  22. +                                o                        +
  23. +                                                          +
  24. +             $                                           +
  25. +                                                          +
  26. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
复制代码
发表于 2023-10-16 20:34:13 | 显示全部楼层
颜色是怎么做的?
您需要登录后才可以回帖 登录 | 注册

本版积分规则

Archiver|手机版|小黑屋|批处理之家 ( 渝ICP备10000708号 )

GMT+8, 2026-3-16 20:57 , Processed in 0.019620 second(s), 9 queries , File On.

Powered by Discuz! X3.5

© 2001-2026 Discuz! Team.

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