我正在尝试使用Python中的curses
库制作类似“Falldown”的游戏,这是我以前在高中玩的TI-83计算器游戏。它涉及一个永远落下的球,你必须通过洞进行操作,如果你没有进入洞,球将被挤压在屏幕的顶部(YouTube它)。
到目前为止,我只有一个甚至没有洞的障碍类。我只想让自己的障碍永远“向上滚动”。我可以使它适用于一个障碍(obs1
),但当我尝试添加第二个(obs2
)时,会发生不好的事情。在下面的代码中,两个障碍物都在屏幕上,但它们正好在彼此的顶部,所以它看起来只是一个障碍。
基本上,当obs2
到达屏幕的一半时,如何启动obs1
?
#!/usr/bin/python
import curses
import time
import random
class obstacle:
def __init__(self):
self.pos = dims[0]-1
self.s = ''
for x in range(0,dims[1]-1):
self.s += '='
def scroll(self):
self.pos -= 1
screen = curses.initscr()
curses.start_color()
curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
screen.nodelay(1)
dims = screen.getmaxyx()
q=-1
obs1 = obstacle()
obs2 = obstacle()
while q < 0:
q = screen.getch()
if obs1.pos < 0:
obs1 = obstacle()
if obs2.pos < 0:
obs2 = obstacle()
screen.clear()
screen.addstr(obs1.pos, 0, obs1.s, curses.color_pair(1))
screen.addstr(obs2.pos, 0, obs2.s, curses.color_pair(1))
obs1.scroll()
obs2.scroll()
screen.refresh()
time.sleep(.04)
screen.getch()
curses.endwin()
最终我会立刻想要屏幕上有4个障碍,永远向上滚动。有什么提示让我开始2?
答案 0 :(得分:0)
你需要思考你想要的东西。在obs2
到达屏幕中途之前obs1
是什么?没事吗?屏幕外的障碍?一个正常工作的障碍,但是没有被画出来?
无论你决定什么都很容易编码。我会挑选最难的并展示如何让它发挥作用:在obs2
足够远之前,我们甚至不会创建obs1
。这意味着我们必须在我们使用它的任何地方检查if obs2 is not None
,然后在适当的时间在某处创建它。所以,像这样:
obs1 = obstacle()
obs2 = None
while q < 0:
q = screen.getch()
if obs1.pos < 0:
obs1 = obstacle()
if obs2 is not None and obs2.pos < 0:
obs2 = obstacle()
# Here's where we create obs2 on the fly
if obs2 is None and obs1.pos == dims[0]/2:
obs2 = obstacle()
screen.clear()
screen.addstr(obs1.pos, 0, obs1.s, curses.color_pair(1))
if obs2 is not None:
screen.addstr(obs2.pos, 0, obs2.s, curses.color_pair(1))
obs1.scroll()
if obs2 is not None:
obs2.scroll()
screen.refresh()
time.sleep(.04)
让我们说我们想要从obs2
开始obs1
偏移一点。在这种情况下,我们只想在第一次使用不同的pos
构建它,而其他所有内容都与原始代码保持不变:
class obstacle:
def __init__(self, offset=1.0):
self.pos = int((dims[0]-1) * offset)
self.s = ''
for x in range(0,dims[1]-1):
self.s += '='
def scroll(self):
self.pos -= 1
screen = curses.initscr()
curses.start_color()
curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
screen.nodelay(1)
dims = screen.getmaxyx()
q=-1
obs1 = obstacle()
obs2 = obstacle(.5)
while q < 0:
q = screen.getch()
if obs1.pos < 0:
obs1 = obstacle()
if obs2.pos < 0:
obs2 = obstacle()
screen.clear()
screen.addstr(obs1.pos, 0, obs1.s, curses.color_pair(1))
screen.addstr(obs2.pos, 0, obs2.s, curses.color_pair(1))
obs1.scroll()
obs2.scroll()
screen.refresh()
time.sleep(.04)
screen.getch()
curses.endwin()