鱼C论坛

 找回密码
 立即注册
查看: 4475|回复: 4

[已解决]如何用python判断键盘是否有输入?

[复制链接]
发表于 2017-7-1 22:54:48 | 显示全部楼层 |阅读模式

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

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

x
背景是这样的,本菜鸟刚起步学习python,无聊时想编写一个“贪吃蛇”的游戏

我引用了msvcrt模块做实时输入用,指令接受环节有如下框架构想:

unknow = msvcrt.getch()  (输入 w a s d)开始等待输入,作为蛇的移动方向
如果在一定时间内(比如0.5秒)系统没有接收到键盘输入,则系统跳过上面抓取字符的语句,直接执行接下来的语句(蛇自动朝着原方向移动一格)

请问这个构架应如何实现?谢谢!!
最佳答案
2017-7-2 10:02:09
一撮痘 发表于 2017-7-1 23:03
代码有200多行很长的。。。如果有大神能提出框架解决方案,或者对代码进行优化的话,小弟感激不尽!!!劳 ...

kbhit
  1. if msvcrt.kbhit():
  2.     key = get_char()
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2017-7-1 22:59:11 | 显示全部楼层
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. __author__ = 'Eric_XU  okbrady@sina.com'

  4. import random as r
  5. import os, msvcrt

  6. # 游戏界面大小
  7. s_Wide = 50
  8. s_Height = 20
  9. table_list = []
  10. tail = (1, int(s_Height/2))
  11. v = {'w': 1, 'a': 2, 's': 4, 'd': 3}
  12. t = [1, 1, 0.8, 0.6, 0.4, 0.3, 0.2]
  13. level = 3

  14. # 清屏程序
  15. def clear_screen():
  16.     os.system('cls')

  17. # 打印标题
  18. def print_title():

  19.     global s_Wide

  20.     title1 = 'SNAKE'
  21.     title2 = 'author: Eric XU  okbrady@sina.com'

  22.     print(title1.center(s_Wide))
  23.     print(title2.center(s_Wide))

  24. # 原始界面的二维列表
  25. def get_table():
  26.     global table_list
  27.     table_list = []
  28.     top_bot = []
  29.     for i in range(s_Wide):
  30.         top_bot.append('-')

  31.     table_list.append(top_bot)

  32.     for i in range(s_Height - 2):
  33.         mid_line = ['|']
  34.         for i in range(s_Wide - 2):
  35.             mid_line.append(' ')
  36.         mid_line.append('|')
  37.         table_list.append(mid_line)

  38.     table_list.append(top_bot)

  39. # 将食物与蛇加入二维列表
  40. def reflash():
  41.     global table_list, snake, food
  42.     get_table()
  43.     b = snake.show_body()
  44.     for i in b:
  45.         temp_x = i[0]
  46.         temp_y = i[1]
  47.         table_list[temp_y][temp_x] = 'O'

  48.     j = food.show_location()
  49.     table_list[j[1]][j[0]] = '*'

  50. # 以字符串形式打印二维列表table_list
  51. def print_table():
  52.     global table_list, s_Height
  53.     for i in range(s_Height):
  54.         temp = ''.join(table_list[i])
  55.         print(temp)

  56. # 边框列表
  57. def edge_list():
  58.     global s_Wide, s_Height
  59.     edge = []
  60.     for i in range(s_Wide):
  61.         edge.extend([(i, 0), (i, s_Height - 1)])
  62.     for j in range(1, s_Height - 1):
  63.         edge.extend([(0, j), (s_Wide - 1, j)])
  64.     return edge
  65. edge = edge_list()

  66. # 定义打印整个屏幕
  67. def print_screen():
  68.     print_title()
  69.     reflash()
  70.     print_table()

  71. # 剩余可以用空格数
  72. def rest():
  73.     global s_Wide, s_Height, snake
  74.     rest_num = (s_Wide-2)*(s_Height-2) - len(snake.show_body())
  75.     return rest_num

  76. class Snake:

  77.     global s_Wide, s_Height, edge

  78.     # 初始参数
  79.     def __init__(self, b, d, s):
  80.         self.body = b
  81.         self.direction = d
  82.         self.status = s

  83.     # 返回蛇身体的列表
  84.     def show_body(self):
  85.         return(self.body)

  86.     # 返回蛇的朝向
  87.     def show_direction(self):
  88.         return(self.direction)

  89.     # 返回蛇的状态
  90.     def show_status(self):
  91.         return(self.status)

  92.     # 返回蛇的尾部
  93.     def show_tail(self):
  94.         return(self.body[-1])

  95.     # 测试是否死亡
  96.     def test_status(self):
  97.         b = self.show_body()
  98.         head = b[0]
  99.         l = len(b)
  100.         corp = []
  101.         for i in range(1, l):
  102.             corp.append(b[i])
  103.         if (head in edge_list()) or (head in corp):
  104.             self.status = False
  105.         else:
  106.             pass

  107.     # 定义移动
  108.     # 吃可以分解为 move() + append(上一步的tail)
  109.     def move(self):
  110.         direct = self.show_direction()
  111.         body_list = self.show_body()
  112.         head = body_list[0]
  113.         (head_x, head_y) = body_list[0]
  114.         l = len(body_list)

  115.         if direct == 'w':
  116.             head_x = head[0]
  117.             head_y = head[1] - 1
  118.         elif direct == 'a':
  119.             head_x = head[0] - 1
  120.             head_y = head[1]
  121.         elif direct == 's':
  122.             head_x = head[0]
  123.             head_y = head[1] + 1
  124.         elif direct == 'd':
  125.             head_x = head[0] + 1
  126.             head_y = head[1]

  127.         new_body = [(head_x, head_y)]
  128.         new_body.extend(body_list[:l-1])
  129.         self.body = new_body


  130. class Food:

  131.     global snake, s_Wide, s_Height

  132.     def __init__(self, l):
  133.         self.location = l

  134.     def show_location(self):
  135.         return self.location

  136.     def reborn(self):
  137.         rest_num = rest()
  138.         temp = r.randint(1, rest_num + 1)
  139.         (temp_x, temp_y) = (0, 1)
  140.         while (temp > 0):
  141.             temp_x += 1
  142.             if temp_x == s_Wide - 1:
  143.                 temp_x = 1
  144.                 temp_y += 1
  145.             if (temp_x, temp_y) not in snake.show_body():
  146.                 temp -= 1
  147.         self.location = (temp_x, temp_y)


  148. # 蛇的初始参数
  149. in_body = [(3, int(s_Height/2)), (2, int(s_Height/2)), (1, int(s_Height/2))]  # 蛇的身体
  150. in_direction = 'w'  # 头的朝向
  151. in_status = True  # 死活

  152. # 定义一条蛇
  153. snake = Snake(in_body, in_direction, in_status)

  154. # 定义食物
  155. food = Food((1, 1))
  156. food.reborn()

  157. # 定义蛇是否吃到了食物
  158. def test_eat():
  159.     global snake, food, tail
  160.     if snake.show_body()[0] == food.show_location():
  161.         food.reborn()
  162.         (snake.show_body()).append(tail)

  163. # 获取字符
  164. def get_char():
  165.     global snake, v
  166.     dir_temp = snake.show_direction()
  167.     unknow = msvcrt.getch()
  168.     char = unknow.decode()
  169.     if ((char in ['w', 'a', 's', 'd']) and (v[char] + v[dir_temp] != 5)):
  170.         return char
  171.     else:
  172.         get_char()

  173. # 主体程序
  174. while snake.show_status():
  175.     clear_screen()
  176.     print_screen()
  177.     key = get_char()
  178.     snake.direction = str(key)
  179.     tail = snake.show_tail()
  180.     snake.move()
  181.     test_eat()
  182.     snake.test_status()
  183. print('Good job! You\'ve just killed yourself!')
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2017-7-1 23:03:41 | 显示全部楼层
代码有200多行很长的。。。如果有大神能提出框架解决方案,或者对代码进行优化的话,小弟感激不尽!!!劳烦大家费心阅读了!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-7-2 10:02:09 | 显示全部楼层    本楼为最佳答案   
一撮痘 发表于 2017-7-1 23:03
代码有200多行很长的。。。如果有大神能提出框架解决方案,或者对代码进行优化的话,小弟感激不尽!!!劳 ...

kbhit
  1. if msvcrt.kbhit():
  2.     key = get_char()
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2017-7-2 10:20:35 | 显示全部楼层

感谢!我的小蛇已经可以自动跑起来了!!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2026-2-28 09:38

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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