【发布时间】:2010-12-30 16:08:36
【问题描述】:
为了帮助大家了解 Objective-C,我正在创建一个非常基本的无 Cocoa 连接 4 游戏。
在我的程序中,我有三个模块:
- “游戏”:包含一个保存棋盘信息的数组。在 main 中创建并负责转弯的对象。 Player 和 Computer 对象位于此模块中。
- “Player”:包含将玩家的棋子插入首选列的函数(此模块的存在是为了封装,仅此而已)。
- “计算机”:包含根据当前电路板设置确定计算机应移动的位置的函数,然后在该位置放置一块。
理想情况下,我希望 Player 和 Computer 类能够通过某种继承来编辑存在于 Game 中的 pieceLoc 的同一个实例,但是我不知道该怎么做。
以下是我目前正在考虑的内容:
// startGame exists within the "Game" module
char *pieceLoc[42]; // This is a *temporary* global var. I'm still learning about
// the best way to implement this with class and instance
// methods. This is the array that holds the board info.
-(void) startGame {
Player *player =[[Player alloc] init]; // player's symbol = 'X'
Computer *computer =[[Computer alloc] init]; // computer's symbol = 'O'
int i = 0;
while ([game hasPieceWon: 'X'] == NO && [game hasPieceWon: 'O'] == NO) {
//function for player move
if ([game hasPieceWon: 'X'] == NO) {
//function for computer move
}
}
if ([game hasPieceWon: 'X'] == YES)
// Tell the player they've won
else
// Tell the player the computer has won.
}
用于玩家和计算机移动的函数是需要以某种方式获得对数组 pieceLoc 的访问权限的函数(一旦我了解了有关类与实例方法的更多信息,它将作为实例变量存在) . pieceLoc 当前以 char * 形式存在,以防我必须通过函数参数传递它。
我觉得这是一个关于我如何考虑 OOP 的相当简单的问题,但是尽管我在下午的大部分时间都在寻找我所寻找的东西,但我还是找不到答案。根据我收集到的信息,我的问题与类组成有关,但我找不到关于 Objective-C 的好资源。
所以,再说一遍:我正在寻找一种方法将位于“父类”游戏中的 pieceLoc 的单个实例传递给两个“子类”,其中 pieceLoc 可以直接被操纵 /em> 使用附加参数。
如果将数组作为参数传递确实是更惯用的做法,我能否获得一个示例,说明在 Objective-C 中按引用传递是如何工作的?
感谢您的帮助!
【问题讨论】:
-
您是否有不喜欢将棋盘信息存储在该全局数组中的原因?
-
Player和Computer是子类吗?
标签: objective-c class composition