Skip to content

Instantly share code, notes, and snippets.

@ajduncan
Created August 30, 2015 02:19
Show Gist options
  • Save ajduncan/7fc78ff66acf04c40d47 to your computer and use it in GitHub Desktop.
Save ajduncan/7fc78ff66acf04c40d47 to your computer and use it in GitHub Desktop.
an example start for a rogue game which uses curses in python
#!/usr/bin/env python
import curses
window = curses.initscr()
def render(stdscr, x, y, msg):
if (x < 0 or y < 0): return
if (x >= curses.LINES or y >= curses.COLS): return
stdscr.addstr(x, y, msg)
class Map:
def __init__(self, stdscr):
self.stdscr = stdscr
self.rooms = []
def addroom(self, room):
self.rooms.append(room)
def draw(self):
for x in range(0, curses.LINES - 1):
for y in range(0, curses.COLS - 1):
render(self.stdscr, x, y, " ")
self.stdscr.refresh()
for r in self.rooms:
for x in range(r.x, r.x+r.width):
for y in range(r.y, r.y+r.height):
if (x > r.x and x < r.x+r.width - 1 and y > r.y and y < r.y+r.height - 1):
render(self.stdscr, x, y, '.')
else:
render(self.stdscr, x, y, '#')
class Room:
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
class Agent:
def __init__(self, stdscr, x, y):
self.x = x
self.y = y
self.stdscr = stdscr
stdscr.addstr(self.y, self.x, '@')
def move(self, direction):
if self.x <= 0 and direction == 'left': return
if self.x >= curses.COLS -2 and direction == 'right': return
if self.y <= 0 and direction == 'up': return
if self.y >= curses.LINES -2 and direction == 'down': return
render(self.stdscr, self.y, self.x, '.')
if direction == 'right':
next_char = chr(self.stdscr.inch(self.y, self.x+1) & 0xff)
if (next_char != '#'):
self.x = self.x + 1
elif direction == 'left':
next_char = chr(self.stdscr.inch(self.y, self.x-1) & 0xff)
if (next_char != '#'):
self.x = self.x - 1
elif direction == 'up':
next_char = chr(self.stdscr.inch(self.y-1, self.x) & 0xff)
if (next_char != '#'):
self.y = self.y - 1
else:
next_char = chr(self.stdscr.inch(self.y+1, self.x) & 0xff)
if (next_char != '#'):
self.y = self.y + 1
render(self.stdscr, self.y, self.x, '@')
def main(stdscr):
stdscr.clear()
curses.curs_set(0)
curses.beep()
curses.flash()
mappa = Map(stdscr)
room1 = Room(10, 10, 10, 25)
mappa.addroom(room1)
mappa.draw()
agent = Agent(stdscr, 11, 11)
while True:
render(stdscr, curses.LINES - 1, 0, 'Position: {0},{1}'.format(agent.x, agent.y))
stdscr.refresh()
c = stdscr.getch()
if c == ord('q'): break
elif c == curses.KEY_RIGHT: agent.move('right')
elif c == curses.KEY_LEFT: agent.move('left')
elif c == curses.KEY_UP: agent.move('up')
elif c == curses.KEY_DOWN: agent.move('down')
else: stdscr.refresh()
curses.wrapper(main)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment