curses包的封装用于实现终端无关的控制台输出以及输入处理。curses包支持各种终端,从古老的VT100到LINUX控制台到X11终端如xterm或rxvt。而python中的curses模块是对curses包的C语言的简单封装,并对curses的调用做了简化,将C接口中的addstr, mvaddstr, mvwaddstr三个函数合并成了一个单独的addstr函数。
前几天在b站上看到一个外国小哥的视频,用curses写了一个简单的贪吃蛇游戏,代码不到80行,感觉很有意思。不过有点小bug,我自己动手实现了一下,做了一些完善并附上了注释,在这里记录并分享一下(注意:curses包只能在linux下使用,如果是windows,可以用unofficial curses)
import curses
import random
# initialize the window
s = curses.initscr()
curses.curs_set(0)
hei, wei = s.getmaxyx() # the value of first getting is y,not x
w = curses.newwin(hei, wei, 0, 0)
w.keypad(1)
w.timeout(100)
# initialize the position of snake
sn_x = int(wei/4)
sn_y = int(hei/2)
snake = [[sn_y, sn_x], [sn_y, sn_x-1], [sn_y, sn_x-2]]
# initialize the position of food
food_pos = [int(hei/2), int(wei/2)]
w.addch(food_pos[0], food_pos[1], '$')
key = curses.KEY_RIGHT
# start
while True:
next_key = w.getch() # The program stops waiting for user input