0

curses我正在尝试使用Python 中的库制作一个类似于“Falldown”的游戏,这是我在高中时玩过的 TI-83 计算器游戏。它涉及一个永远下落的球,你必须通过洞来操纵它,如果你没有进入洞,球会在屏幕顶部被压扁(YouTube it)。

到目前为止,我只有一个甚至还没有漏洞的障碍类。我只希望我的障碍永远“向上滚动”。我可以让它为一个障碍(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 开始吗?

4

1 回答 1

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()
于 2013-01-26T01:04:37.483 回答