Files
RPG_curses/world.py
2025-05-18 11:48:19 +08:00

86 lines
2.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import random
import curses
from config import objects, player, camera
from inventory import inventory_add # 我们会在 inventory.py 里提供这个函数
def init_objects(width, height):
objects.clear()
# 全局范围随机生成
for _ in range(99999):
x = random.randint(-2000, 2000)
y = random.randint(-2000, 2000)
# 随机决定生成绿或红10% 红90% 绿
typ = "red" if random.random() < 0.10 else "green"
objects[(x, y)] = typ
# 保证初始视野内也有一些
camx, camy = camera["x"], camera["y"]
for _ in range(200):
x = random.randint(camx, camx + width - 1)
y = random.randint(camy, camy + height - 1)
typ = "red" if random.random() < 0.10 else "green"
objects[(x, y)] = typ
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:
typ = objects[(wx, wy)]
pair = 5 if typ == "red" else 2
stdscr.addstr(y, x, "*", curses.color_pair(pair))
stdscr.refresh()
def game_loop(stdscr, width, height):
stdscr.nodelay(True)
stdscr.timeout(50)
while True:
draw_map(stdscr, width, height)
key = stdscr.getch()
# ESC 退出
if key == 27:
break
# 方向键移动
elif 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
# 摄像机跟随
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)
typ = "red" if random.random() < 0.10 else "green"
objects[(ox, oy)] = typ
# 检测拾取
pos = (player["x"], player["y"])
if pos in objects:
typ = objects.pop(pos)
# 调用 inventory 系统加入背包
inventory_add(typ)
# 临时提示
stdscr.addstr(height, 0,
f"Picked up a {typ} item!",
curses.color_pair(4))
stdscr.refresh()
curses.napms(300)