二十一点游戏的数据结构
我正在尝试学习如何使用 Ruby,作为我的第一个应用程序,我想构建一个基于控制台的 Blackjack 游戏。
我对 Ruby 结构不太熟悉,唯一能让我学习并感到宾至如归的方法就是构建东西并从错误中学习。
我正在考虑创建一个 Card 类,并且有一个 Stack 类有一个 Card 集合。
但是我不确切知道需要使用什么内置类型来保存这些 Card 对象。
这是我的卡片类:
class Card
attr_accessor :number, :suit
def initialize(number, suit)
@number = number
@suit = suit
end
def to_s
"#{@number} of #{@suit}"
end
end
因为我来自 C#,所以我想到使用类似 List Cards {get;set;} 的东西 - Ruby 中存在这样的东西,或者也许有更好的、更红宝石式的方法来做到这一点。
I'm trying to learn how to use Ruby and as my first application I'd like to build a console based Blackjack game.
I'm not too familiar with the Ruby constructs and the only way I'll learn and feel at home is build things and learn from my mistakes.
I'm thinking of creating a Card class, and has a Stack class has a collection of Cards.
However I don't know exactly what built in type I need to use to hold these Card objects.
Here is my card class:
class Card
attr_accessor :number, :suit
def initialize(number, suit)
@number = number
@suit = suit
end
def to_s
"#{@number} of #{@suit}"
end
end
Since I'm coming from C#, I thought of using something like List Cards {get;set;} - does something like this exists in Ruby or maybe there is a better more rubyesque way to do this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Ruby 是一种动态语言,因此它通常不依赖于严格的编译时类型检查,因此使得诸如模板化
List
之类的构造相当无用。 Ruby 通常有一种通用的有序集合数据类型 - Array,它非常模仿 Java/C# 的 ArrayList 概念。因此,除非您希望 Stack 变得特殊,否则您可以按原样使用 Array :
或以某种方式扩展 Array :
Ruby is a dynamic language, so it usually doesn't rely on strict compile-time type checking, thus making constructions, such as templatized
List<Card>
fairly useless. Ruby generally has one universal data type of ordered collections -Array
, which closely mimicsArrayList
concept of Java/C#.So, unless you want
Stack
to be something special, you can just useArray
as is:or extend
Array
in some way:Ruby 的内置
Array
类型具有类似于堆栈的方法:Ruby's builtin
Array
type has methods for acting like a stack:两集 Ruby Quiz 专门针对二十一点。第二个的解决方案可能会给您一些想法: http://www.rubyquiz.com/quiz151.html
Two Ruby Quiz episodes were dedicated to blackjack. The solutions to the second one might give you some ideas: http://www.rubyquiz.com/quiz151.html