# inventory.py import curses class Inventory: def __init__(self, cols=5, rows=4): self.cols = cols self.rows = rows self.slots = {i: None for i in range(cols * rows)} for i, ch in enumerate(["S", "H", "P"]): if i < cols * rows: self.slots[i] = ch self.held = None self.held_pos = (0, 0) def draw(self, stdscr, scr_w, scr_h): side = int(min(scr_w, scr_h) * 0.6) cell = (side - 2) // max(self.cols, self.rows) win_w = cell * self.cols + 2 win_h = cell * self.rows + 2 sx = (scr_w - win_w) // 2 sy = (scr_h - win_h) // 2 win = curses.newwin(win_h, win_w, sy, sx) win.bkgd(' ', curses.color_pair(3)) win.box() for idx in range(self.cols * self.rows): r, c = divmod(idx, self.cols) y0 = 1 + r * cell x0 = 1 + c * cell # 绘格子 for x in range(x0, x0+cell): win.addch(y0, x, curses.ACS_HLINE) win.addch(y0+cell-1, x, curses.ACS_HLINE) for y in range(y0, y0+cell): win.addch(y, x0, curses.ACS_VLINE) win.addch(y, x0+cell-1, curses.ACS_VLINE) win.addch(y0, x0, curses.ACS_ULCORNER) win.addch(y0, x0+cell-1, curses.ACS_URCORNER) win.addch(y0+cell-1, x0, curses.ACS_LLCORNER) win.addch(y0+cell-1, x0+cell-1, curses.ACS_LRCORNER) # 画字母 ch = self.slots.get(idx) if ch: win.addch(y0 + cell//2, x0 + cell//2, ch, curses.color_pair(2)) win.refresh() if self.held: my, mx = self.held_pos if 0 <= my < scr_h and 0 <= mx < scr_w: stdscr.addch(my, mx, self.held, curses.color_pair(2)) stdscr.refresh() return (sy, sx, win_h, win_w) def click(self, my, mx, area): sy, sx, h, w = area if not (sy <= my < sy+h and sx <= mx < sx+w): return rel_y, rel_x = my-sy-1, mx-sx-1 cell_h = (h-2)//self.rows cell_w = (w-2)//self.cols r = rel_y // cell_h c = rel_x // cell_w if 0 <= r < self.rows and 0 <= c < self.cols: idx = r*self.cols + c if self.held: if self.slots.get(idx) is None: self.slots[idx] = self.held self.held = None else: ch = self.slots.get(idx) if ch: self.held = ch self.slots[idx] = None def move(self, my, mx): self.held_pos = (my, mx)