2016-09-15 59 views
1

所以我開始在Python中使用Curses。 我有這個源代碼入手,慢慢地我會做一些更新,它:使用Python編程的詛咒程序

#!/usr/bin/env python3 
# -*- coding: utf-8 -*- 

""" 
Testing out the curses lib. 
""" 

import curses 


def main(scr): 
    """ 
    Draw a border around the screen, move around using the cursor and leave a mark 
    of the latest pressed character on the keyboard. 

    Perhaps you could make a nice painting using asciart? 

    Quit using 'q'. 
    """ 

    # Clear the screen of any output 
    scr.clear() 

    # Get screen dimensions 
    y1, x1 = scr.getmaxyx() 
    y1 -= 1 
    x1 -= 1 

    y0, x0 = 0, 0 

    # Get center position 
    yc, xc = (y1-y0)//2, (x1-x0)//2 

    # Draw a border 
    scr.border() 

    # Move cursor to center 
    scr.move(yc, xc) 

    # Refresh to draw out 
    scr.refresh() 

    # Main loop 
    x = xc 
    y = yc 
    ch = 'o' 

    while True: 
     key = scr.getkey() 
     if key == 'q': 
      break 
     elif key == 'KEY_UP': 
      y -= 1 
     elif key == 'KEY_DOWN': 
      y += 1 
     elif key == 'KEY_LEFT': 
      x -= 1 
     elif key == 'KEY_RIGHT': 
      x += 1 
     else: 
      ch = key 

     # Draw out the char at cursor position 
     scr.addstr(ch) 

     # Move cursor to new position 
     scr.move(y, x) 

     # Redraw all items on the screen 
     scr.refresh() 



if __name__ == "__main__": 
    print(__doc__) 
    print(main.__doc__) 
    input("Press enter to begin playing...") 
    curses.wrapper(main) 

我現在要做的事情是要確保當我不能打在屏幕的邊框。但我不確定這個功能是什麼,我可以使用它。 我已閱讀python docs,但無法找到任何我認爲可行的內容。

回答

2

你知道有效範圍。從0y1(含)。 (分別爲0至x1)。所以只需添加測試,以確保座標留的範圍內:

elif key == 'KEY_UP': 
     if y > 0: 
     y -= 1 
    elif key == 'KEY_DOWN': 
     if y < y1: 
     y += 1 

,爲x相似。

+0

謝謝垂直! – anderssinho