{ }codelper
方法P0346

会用字符串报告自己状态的游戏角色

请用类来实现游戏角色。
角色对象的字段有名字、最大体力 m 和当前体力。
当前体力从 m 开始。
给角色写三个方法。
hit(d) 把体力减少 d。
但体力不会小于 0,减到 0 就停住。
heal(h) 把体力增加 h。
但体力不会大于 m,加到 m 就停住。
体力为 0 的角色已经倒下,即使得到恢复也不发生任何变化。
状态字符串方法把角色变成 "名字 体力/m" 形式的字符串并返回(例如 ann 7/10)。
体力为 0 时,在后面再加一个空格和 down(例如 ann 0/10 down)。
状态字符串方法请用该语言把对象转成字符串时会调用的名字来写(Python __str__,Java、JS、TS toString,C# ToString,C++ operator<<)。
第一行给出角色数 n 和命令数 q。
接下来 n 行,每行给出 1 号到 n 号角色的名字和最大体力 m。
接下来 q 行,每行给出一条命令。
hit i d 调用 i 号角色的 hit(d),heal i h 调用 i 号角色的 heal(h)。
每处理一条命令,就在一行中输出 i 号角色的状态字符串。
处理完所有命令后,在最后一行输出没有倒下(体力不小于 1)的角色数。
评测只看输出,所以不检查方法是怎么划分的。

输入
1 ≤ n ≤ 100,1 ≤ q ≤ 1,000,1 ≤ m ≤ 1,000,1 ≤ i ≤ n,1 ≤ d ≤ 1,000,1 ≤ h ≤ 1,000(都是整数,只给出数字,不带逗号)。
名字由 1~10 个英文小写字母或数字组成,可能有多个角色同名。
一行中的值用一个空格隔开
输出
每条命令一行,共 q 行,最后一行是没有倒下的角色数
样例 1 · stdin
2 6
ann 10
bo 5
hit 1 3
heal 1 5
hit 2 9
heal 2 3
hit 1 4
hit 2 1
stdout
ann 7/10
ann 10/10
bo 0/5 down
bo 0/5 down
ann 6/10
bo 0/5 down
1
main.py
输入(stdin)

运行时这些行会依次作为 input()/标准输入传入(运行中不会等待输入)。

$ 就绪

请在电脑上打开以编写和运行代码。在手机上可以查看题目和题解。

其他语言怎么写?查看各语言题解 · 6 种语言题解

本题只接受有类和方法的 Python、JavaScript、TypeScript、Java、C#、C++(C 没有方法,Craykon 还不能定义类)。
方法是改变对象所持有的值(hit、heal),或者用这些值算出结果并返回(状态字符串)的函数。
把对象转成字符串的方法,各语言都有固定的名字。
Python 写 __str__,print(hero) 和 str(hero) 就会调用它。
Java 写 toString(),System.out.println(hero) 和 "" + hero 会调用它;C# 写 override string ToString(),Console.WriteLine(hero) 和 $"{hero}" 会调用它。
JS、TS 写 toString(),` ${hero} 、String(hero)、"" + hero` 会调用它。
C++ 没有这样的方法,所以要写 operator<<,让 cout << hero 能用。
陷阱一:JS 的 console.log(hero) 不调用 toString,而是显示对象的内部,于是示例的第一行变成 Hero { name: 'ann', maxHp: 10, hp: 7 }。
陷阱二:在 C# 里不写 override,只写 public string ToString(),只会有警告,仍能编译。
但 StringBuilder.Append(hero) 调用的是原来的 object.ToString(),所以每一行都只有类名 Hero。
陷阱三:在 Java 里把名字写成 tostring() 这样不同的拼法,它只是一个新方法,输出会是 Main$Hero@55f96302 这样的字符串。
在方法上面加 @Override,这种拼写错误就会变成编译错误。
陷阱四:把体力限制在 0 和 m 之间的工作要在方法里做。
直接存入 hp - d,示例的第三行会变成 bo -4/5;直接存入 hp + h,第二行会变成 ann 12/10。
Python 用 max(0, …)、min(m, …),JS、TS、Java 用 Math.max、Math.min,C# 用 Math.Max、Math.Min,C++ 用 std::max、std::min。
陷阱五:heal 里要先问角色是否已经倒下。
不问的话,示例的第四行会变成 bo 3/5,倒下的角色又站了起来。

Pythonmain.py · 47 行
import sys  class Hero:    def __init__(self, name, max_hp):        self.name = name        self.max_hp = max_hp        self.hp = max_hp  # 체력은 가득 찬 채로 시작한다     def hit(self, d):        self.hp = max(0, self.hp - d)  # 0보다 작아지지 않는다     def heal(self, h):        if self.hp == 0:  # 쓰러진 캐릭터는 회복하지 못한다            return        self.hp = min(self.max_hp, self.hp + h)     def is_down(self):        return self.hp == 0     # print(hero)·str(hero)·f"{hero}"가 부르는 메서드    def __str__(self):        text = f"{self.name} {self.hp}/{self.max_hp}"        return text + " down" if self.is_down() else text  def main():    lines = sys.stdin.read().split("\n")    n, q = map(int, lines[0].split())    heroes = []    for i in range(1, n + 1):        name, m = lines[i].split()        heroes.append(Hero(name, int(m)))    out = []    for i in range(n + 1, n + 1 + q):        cmd, idx, amount = lines[i].split()        hero = heroes[int(idx) - 1]        if cmd == "hit":            hero.hit(int(amount))        else:            hero.heal(int(amount))        out.append(str(hero))    out.append(str(sum(1 for h in heroes if not h.is_down())))    print("\n".join(out))  main()
JavaScriptmain.js · 44 行
class Hero {  constructor(name, maxHp) {    this.name = name;    this.maxHp = maxHp;    this.hp = maxHp; // 체력은 가득 찬 채로 시작한다  }   hit(d) {    this.hp = Math.max(0, this.hp - d); // 0보다 작아지지 않는다  }   heal(h) {    if (this.hp === 0) return; // 쓰러진 캐릭터는 회복하지 못한다    this.hp = Math.min(this.maxHp, this.hp + h);  }   isDown() {    return this.hp === 0;  }   // `${hero}`·String(hero)·"" + hero 가 부르는 메서드  toString() {    const text = `${this.name} ${this.hp}/${this.maxHp}`;    return this.isDown() ? text + " down" : text;  }} const lines = require("fs").readFileSync(0, "utf8").split("\n");const [n, q] = lines[0].trim().split(" ").map(Number);const heroes = [];for (let i = 1; i <= n; i++) {  const [name, m] = lines[i].trim().split(" ");  heroes.push(new Hero(name, Number(m)));}const out = [];for (let i = n + 1; i <= n + q; i++) {  const [cmd, idx, amount] = lines[i].trim().split(" ");  const hero = heroes[Number(idx) - 1];  if (cmd === "hit") hero.hit(Number(amount));  else hero.heal(Number(amount));  out.push(`${hero}`); // console.log(hero)는 toString을 부르지 않는다}out.push(String(heroes.filter((h) => !h.isDown()).length));console.log(out.join("\n"));
TypeScriptmain.ts · 46 行
import { readFileSync } from "node:fs"; class Hero {  private hp: number;   constructor(private readonly name: string, private readonly maxHp: number) {    this.hp = maxHp; // 체력은 가득 찬 채로 시작한다  }   hit(d: number): void {    this.hp = Math.max(0, this.hp - d); // 0보다 작아지지 않는다  }   heal(h: number): void {    if (this.hp === 0) return; // 쓰러진 캐릭터는 회복하지 못한다    this.hp = Math.min(this.maxHp, this.hp + h);  }   isDown(): boolean {    return this.hp === 0;  }   // `${hero}`·String(hero)가 부르는 메서드  toString(): string {    const text = `${this.name} ${this.hp}/${this.maxHp}`;    return this.isDown() ? text + " down" : text;  }} const lines: string[] = readFileSync(0, "utf8").split("\n");const [n, q] = lines[0].trim().split(" ").map(Number);const heroes: Hero[] = [];for (let i = 1; i <= n; i++) {  const [name, m] = lines[i].trim().split(" ");  heroes.push(new Hero(name, Number(m)));}const out: string[] = [];for (let i = n + 1; i <= n + q; i++) {  const [cmd, idx, amount] = lines[i].trim().split(" ");  const hero = heroes[Number(idx) - 1];  if (cmd === "hit") hero.hit(Number(amount));  else hero.heal(Number(amount));  out.push(`${hero}`); // console.log(hero)는 toString을 부르지 않는다}out.push(String(heroes.filter((h) => !h.isDown()).length));console.log(out.join("\n"));
JavaMain.java · 64 行
import java.io.BufferedReader;import java.io.InputStreamReader;import java.util.StringTokenizer; public class Main {    static class Hero {        private final String name;        private final int maxHp;        private int hp;         Hero(String name, int maxHp) {            this.name = name;            this.maxHp = maxHp;            this.hp = maxHp; // 체력은 가득 찬 채로 시작한다        }         void hit(int d) {            hp = Math.max(0, hp - d); // 0보다 작아지지 않는다        }         void heal(int h) {            if (hp == 0) return; // 쓰러진 캐릭터는 회복하지 못한다            hp = Math.min(maxHp, hp + h);        }         boolean isDown() {            return hp == 0;        }         // println(hero)와 "" + hero 가 부르는 메서드. @Override가 이름 오타를 잡아 준다        @Override        public String toString() {            String text = name + " " + hp + "/" + maxHp;            return isDown() ? text + " down" : text;        }    }     public static void main(String[] args) throws Exception {        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));        StringTokenizer st = new StringTokenizer(br.readLine());        int n = Integer.parseInt(st.nextToken());        int q = Integer.parseInt(st.nextToken());        Hero[] heroes = new Hero[n];        for (int i = 0; i < n; i++) {            st = new StringTokenizer(br.readLine());            String name = st.nextToken();            heroes[i] = new Hero(name, Integer.parseInt(st.nextToken()));        }        StringBuilder sb = new StringBuilder();        for (int i = 0; i < q; i++) {            st = new StringTokenizer(br.readLine());            String cmd = st.nextToken();            Hero hero = heroes[Integer.parseInt(st.nextToken()) - 1];            int amount = Integer.parseInt(st.nextToken());            if (cmd.equals("hit")) hero.hit(amount);            else hero.heal(amount);            sb.append(hero).append('\n'); // append(객체)가 toString을 부른다        }        int up = 0;        for (Hero h : heroes) if (!h.isDown()) up++;        sb.append(up).append('\n');        System.out.print(sb);    }}
C#Main.cs · 65 行
using System;using System.Text; class Hero{    private readonly string name;    private readonly int maxHp;    private int hp;     public Hero(string name, int maxHp)    {        this.name = name;        this.maxHp = maxHp;        hp = maxHp; // 체력은 가득 찬 채로 시작한다    }     public void Hit(int d)    {        hp = Math.Max(0, hp - d); // 0보다 작아지지 않는다    }     public void Heal(int h)    {        if (hp == 0) return; // 쓰러진 캐릭터는 회복하지 못한다        hp = Math.Min(maxHp, hp + h);    }     public bool IsDown => hp == 0;     // Console.WriteLine(hero)와 $"{hero}"가 부르는 메서드. override를 빼면 불리지 않는다    public override string ToString()    {        string text = $"{name} {hp}/{maxHp}";        return IsDown ? text + " down" : text;    }} class Program{    static void Main()    {        string[] first = Console.ReadLine()!.Trim().Split(' ');        int n = int.Parse(first[0]), q = int.Parse(first[1]);        var heroes = new Hero[n];        for (int i = 0; i < n; i++)        {            string[] p = Console.ReadLine()!.Trim().Split(' ');            heroes[i] = new Hero(p[0], int.Parse(p[1]));        }        var sb = new StringBuilder();        for (int i = 0; i < q; i++)        {            string[] p = Console.ReadLine()!.Trim().Split(' ');            Hero hero = heroes[int.Parse(p[1]) - 1];            int amount = int.Parse(p[2]);            if (p[0] == "hit") hero.Hit(amount);            else hero.Heal(amount);            sb.Append(hero).Append('\n'); // Append(객체)가 ToString을 부른다        }        int up = 0;        foreach (Hero h in heroes) if (!h.IsDown) up++;        sb.Append(up).Append('\n');        Console.Write(sb);    }}
C++main.cpp · 58 行
#include <algorithm>#include <iostream>#include <string>#include <vector>using namespace std; class Hero {    string name_;    int max_hp_;    int hp_; public:    Hero(const string& name, int max_hp) : name_(name), max_hp_(max_hp), hp_(max_hp) {}     void hit(int d) { hp_ = max(0, hp_ - d); }  // 0보다 작아지지 않는다     void heal(int h) {        if (hp_ == 0) return;  // 쓰러진 캐릭터는 회복하지 못한다        hp_ = min(max_hp_, hp_ + h);    }     bool is_down() const { return hp_ == 0; }     // C++에는 toString이 없다. cout << hero 가 되도록 << 연산자를 만들어 준다    friend ostream& operator<<(ostream& os, const Hero& h) {        os << h.name_ << ' ' << h.hp_ << '/' << h.max_hp_;        if (h.is_down()) os << " down";        return os;    }}; int main() {    ios::sync_with_stdio(false);    cin.tie(nullptr);    int n, q;    cin >> n >> q;    vector<Hero> heroes;    for (int i = 0; i < n; i++) {        string name;        int m;        cin >> name >> m;        heroes.emplace_back(name, m);    }    for (int i = 0; i < q; i++) {        string cmd;        int idx, amount;        cin >> cmd >> idx >> amount;        Hero& hero = heroes[idx - 1];  // &가 없으면 복사본을 고치게 된다        if (cmd == "hit") hero.hit(amount);        else hero.heal(amount);        cout << hero << '\n';    }    int up = 0;    for (const Hero& h : heroes)        if (!h.is_down()) up++;    cout << up << '\n';    return 0;}