最终:账户转账
Coddy 面向 PHP 开发者的 GDScript 课程的第 48 课,共 48 课。
挑战
简单实现 FundsAccount(initial:int),其中包含 balance;实现静态方法 FundsTransfer.move(source:FundsAccount,target:FundsAccount,n:int)->bool。如果账户为 null、金额为负数或 source 资金不足,则拒绝转账且不修改任何内容。否则转账一次。金额足够时,向自身转账会成功,余额不变。Solve 接收 [a,b,n],并返回 success:a:b。初始余额均为非负数。
输入是 stdin 上的一个 JSON 数组。锁定的 main 会解析它,调用公开 API,并打印 result=,后面跟着返回的文本和一个换行符。任何辅助函数都不应打印内容。在处理输入用例之前,独立的固定探测会验证所需的 API 行为;它们不会限制实现风格。
你的代码写在 funds_account.gd、funds_transfer.gd 和 exercise.gd 中。main.gd 包含提供的输入/输出代码,不能编辑。每个 class_name 类型都要放在对应名称的文件中。
完整的 PHP 参考程序。每个文件都完整展示;使用 PHP 8.3 CLI 运行 main.php,输入与本任务相同的 JSON 数组。
PHP 文件 FundsAccount.php:
<?php
declare(strict_types=1);
class FundsAccount {
public function __construct(public int $balance=0) {}
}
PHP 文件 FundsTransfer.php:
<?php
declare(strict_types=1);
class FundsTransfer {
public static function move(?FundsAccount $source,?FundsAccount $target,int $amount): bool {
if($source===null || $target===null || $amount<0 || $amount>$source->balance) return false;
$source->balance-=$amount;
$target->balance+=$amount;
return true;
}
}
PHP 文件 main.php:
<?php
declare(strict_types=1);
require_once __DIR__."/FundsAccount.php";
require_once __DIR__."/FundsTransfer.php";
[$a,$b,$amount]=json_decode(stream_get_contents(STDIN),true,512,JSON_THROW_ON_ERROR);
$source=new FundsAccount($a); $target=new FundsAccount($b);
$success=FundsTransfer::move($source,$target,$amount);
echo "result=",json_encode($success),":",$source->balance,":",$target->balance,"\n";
亲手试试
extends Node
func contract_ok(data: Array) -> bool:
var a: FundsAccount = FundsAccount.new(6)
var b: FundsAccount = FundsAccount.new(2)
if FundsTransfer.move(null,b,0) or FundsTransfer.move(a,null,0) or FundsTransfer.move(a,b,7) or FundsTransfer.move(a,b,-1): return false
if a.balance != 6 or b.balance != 2: return false
if not FundsTransfer.move(a,a,4) or a.balance != 6: return false
if not FundsTransfer.move(a,b,3) or a.balance != 3 or b.balance != 5: return false
return true
func _ready() -> void:
var data: Array = JSON.parse_string(OS.read_string_from_stdin())
if not contract_ok(data):
print("API_CONTRACT_FAILED")
return
print("result=" + Exercise.solve(data))
面向 PHP 开发者的 GDScript中的所有课
自己练习: GDScript 在线编译器