RCRPG/Tcl: Difference between revisions

Minor improvements for readability
(+ version with encapsulated setter/getter)
(Minor improvements for readability)
Line 1:
{{collection|RCRPG}}[[Category:Tcl]]This version of [[RCRPG]] was typed and tested on a cellphone, so pardon my brevity.
 
<lang Tcl>#!/usr/bin/env tclsh
#!/usr/bin/env tclsh
proc help args {
return "RosettaCode 3D single user dungeon in Tcl. Type a command:
Line 11 ⟶ 10:
i(nventory) : get told what you have
For going up, you also need a ladder."}
 
proc main argv {
Room 0,0,0 StartRoom sledge
Line 30:
}
}
 
proc Room {xyz {name {}} {items {}}} { #-- "constructor"
if {$name eq ""} {set name R.[incr ::R()]}
Line 35 ⟶ 36:
array set ::R [list $xyz.name $name $xyz.items $items $xyz.exits {}]
}
 
proc Inverse where {
switch -- $where {
Line 43 ⟶ 45:
}
}
 
proc Normalize where {
switch -- $where {
Line 50 ⟶ 53:
}
}
 
proc attack where {
if {"sledge" ni $::Self(items)} {return "need sledge to attack!"}
Line 66 ⟶ 70:
describe
}
 
proc describe {} {
set xyz $::Self(coords)
Line 80 ⟶ 85:
inventory
}
 
proc drop what {
set xyz $::Self(coords)
Line 90 ⟶ 96:
inventory
}
 
proc go {where {describe 1}} {
set where [Normalize $where]
Line 109 ⟶ 116:
if $describe describe
}
 
proc inventory {} {
return "You have [pretty $::Self(items)]."
}
 
proc name what {
set ::R($::Self(coords).name) $what
return "This room is now named $what."
}
 
proc take what {
set xyz $::Self(coords)
Line 126 ⟶ 136:
inventory
}
 
#--- general utilities
proc alias {new = args} {interp alias {} $new {} {*}$args}
Line 143 ⟶ 154:
main $argv</lang>
 
==Alternative Version==
The following version is functionally identical, but uses a setter/getter function "@" to hide away the data representation
from most of the code (except in the definition of "@" itself).
Line 183 ⟶ 195:
}
}
 
proc Room {xyz {name {}} {items {}}} { #-- "constructor"
if {$name eq ""} {set name R.[incr ::ID]}
Line 190 ⟶ 203:
@ $xyz exits {}
}
 
proc Inverse where {
switch -- $where {
Line 198 ⟶ 212:
}
}
 
proc Normalize where {
switch -- $where {
Line 204 ⟶ 219:
}
}
 
proc @ {coords what {value --}} { #-- universal setter/getter
if {$coords eq "my"} {
Line 215 ⟶ 231:
} else {set ::R($coords.$what) $value}
}
 
#------------------- commands in Afferbeck Lauder
proc attack where {
Line 235 ⟶ 252:
describe
}
 
proc describe {} {
set coords [@ my coords]
Line 247 ⟶ 265:
inventory
}
 
proc drop what {
if {$what eq "all"} {set what [@ my items]}
Line 256 ⟶ 275:
inventory
}
 
proc go {where {describe 1}} {
set where [Normalize $where]
Line 276 ⟶ 296:
if $describe describe
}
 
proc inventory {} {return "You have [pretty [@ my items]]."}
proc name what {
return "This room is now named [@ here name $what]."
}
 
proc take what {
if {$what eq "all"} {set what [@ here items]}
Line 289 ⟶ 311:
inventory
}
 
#----------------------- general utilities
proc alias {new = args} {interp alias {} $new {} {*}$args}
Anonymous user