Files
o.nmgjg.com.cn/RPG_Sample/world.py
Tommmy 17b314407f 上传文件至 RPG_Sample
一个纯终端的RPG游戏基本样例
包含键盘、鼠标交互等

Signed-off-by: Tommmy <pinetree985@gmail.com>
2025-05-14 08:19:41 +08:00

95 lines
2.9 KiB
Python

# world.py
import random
import curses
from config import objects, player, camera
from inventory import Inventory
inventory = Inventory(cols=5, rows=4)
show_inv = False
inv_area = None
def init_objects(width, height):
objects.clear()
for _ in range(99999):
x = random.randint(-2000, 2000)
y = random.randint(-2000, 2000)
objects.add((x, y))
camx, camy = camera["x"], camera["y"]
for _ in range(200):
x = random.randint(camx, camx+width-1)
y = random.randint(camy, camy+height-1)
objects.add((x, y))
def draw_map(stdscr, width, height):
stdscr.clear()
for y in range(height):
for x in range(width):
wx, wy = camera["x"]+x, camera["y"]+y
if (wx,wy)==(player["x"],player["y"]):
stdscr.addstr(y,x,"@",curses.color_pair(1))
elif (wx,wy) in objects:
stdscr.addstr(y,x,"*",curses.color_pair(2))
stdscr.refresh()
def game_loop(stdscr, width, height):
global show_inv, inv_area
stdscr.keypad(True)
curses.mousemask(curses.ALL_MOUSE_EVENTS | curses.REPORT_MOUSE_POSITION)
curses.mouseinterval(0)
curses.putp(b"\033[?1003h")
stdscr.nodelay(True)
stdscr.timeout(30)
try:
while True:
draw_map(stdscr, width, height)
if show_inv:
inv_area = inventory.draw(stdscr, width, height)
key = stdscr.getch()
if key == ord('e'):
show_inv = not show_inv
stdscr.clear()
continue
if show_inv and key == curses.KEY_MOUSE:
_, mx, my, _, bstate = curses.getmouse()
inventory.move(my, mx)
if bstate & curses.BUTTON1_PRESSED:
inventory.click(my, mx, inv_area)
continue
# ←↑→↓ 控制
if key == curses.KEY_UP:
player["y"] -= 1
elif key == curses.KEY_DOWN:
player["y"] += 1
elif key == curses.KEY_LEFT:
player["x"] -= 1
elif key == curses.KEY_RIGHT:
player["x"] += 1
elif key == 27:
break
if player["x"]-camera["x"]<20: camera["x"]-=1
elif player["x"]-camera["x"]>width-21: camera["x"]+=1
if player["y"]-camera["y"]<7: camera["y"]-=1
elif player["y"]-camera["y"]>height-8: camera["y"]+=1
if random.random()<0.01:
ox = random.randint(player["x"]-20,player["x"]+20)
oy = random.randint(player["y"]-20,player["y"]+20)
objects.add((ox,oy))
pos = (player["x"],player["y"])
if pos in objects:
objects.remove(pos)
stdscr.addstr(height,0,"You picked up an item!",curses.color_pair(4))
stdscr.refresh()
curses.napms(300)
finally:
curses.putp(b"\033[?1003l")