Позвольте мне объяснить концепцию кирпичами, прежде чем начинать с вопросов.
Игра представляет собой головоломку. У меня есть сетка, которая 6x6. У меня есть кирпичи на всех квадратах сетки, кроме одного. Причина пустого квадрата (который всегда начинается с 5x5 в начале игры) состоит в том, что кирпичи смогут двигаться только в том случае, если рядом с ними есть пустой квадрат. Направление, в котором они будут двигаться, будет к пустому квадрату. Другими словами, они затем поменяются местами с пустым квадратом при касании. Можно сказать, что движущиеся и визуальные части выглядят почти как игра-слайдер. Хотя концепция игры иная.
Мой первый вопрос: я почему-то могу двигать кирпичи только в одном направлении. Я должен быть в состоянии переместить их во всех четырех направлениях (ВВЕРХ, ВНИЗ, ВЛЕВО, ВПРАВО). Я проверил с NSLog и увидел, что это только UIImages на экране, которые обновляются до новых позиций. не фактическая позиция внутри кода. другими словами ... код, кажется, думает, что кирпичи все еще находятся в начальной позиции, даже после того, как кирпич на экране переместился в другой квадрат. Каков наилучший способ «обновить» позиции внутри кода, чтобы я мог двигаться в любом из четырех направлений?
Мой второй вопрос заключается в том, что кирпич, который расположен в позиции 4x5 на сетке (слева от пустого квадрата), кажется, получает две позиции "по цене одной", когда я чекаю с NSLog. это приводит к тому, что кирпич становится «дезориентированным» и не будет двигаться должным образом, что является лишь одним шагом. кирпич должен получить только одну позицию: x = 4 y = 5, а не x = 4 y = 5, x = 5 y = 5. Я поместил проблему в пустой квадрат на сетке. без этого движение кирпичей хорошо. Есть ли способ решить эту проблему, так как пустой квадрат является частью игры?
IBOutlet UIImageView *grid[BRICKWIDTH][BRICKHEIGHT];
NSString *brickTypes[6];
//Putting the bricks on the grid
-(void)createbricks{
brickTypes[0] = @"Ch'en.png";
brickTypes[1] = @"K'ank'in.png";
brickTypes[2] = @"K'ayab'.png";
brickTypes[3] = @"kej.png";
brickTypes[4] = @"kumk'u.png";
brickTypes[5] = @"mak.png";
//empty spot in the bottom right corner of the grid
blankPosition = CGPointMake(5, 5);
int Bx = blankPosition.x;
int By = blankPosition.y;
NSLog(@"CreateBricks, Startposition, blankPosition.x = Bx: %d", Bx);
NSLog(@"CreateBricks, Startposition, blankPosition.y = By: %d", By);
for (int y = 0; y < BRICKHEIGHT; y++)
{
for (int x = 0; x < BRICKWIDTH; x++)
{
CGPoint orgPosition = CGPointMake(x,y);
if( blankPosition.x == orgPosition.x && blankPosition.y == orgPosition.y ){
continue;
}
UIImage *image = [UIImage imageNamed: brickTypes [rand() % 6]];
grid[x][y] = [[[UIImageView alloc] initWithImage:image] autorelease];
CGRect newFrame = grid[x][y].frame;
newFrame.origin = CGPointMake((x * 48)+52, (y * 49)+7);
grid[x][y].frame = newFrame;
[self.view addSubview:grid[x][y]];
NSLog(@"Grid x: %d", x);
NSLog(@"Grid y: %d", y);
[image release];
}
}
}
//Valid moves: UP, DOWN, LEFT or RIGHT
-(Move) validMove:(int) brickX Yposition: (int) brickY{
NSLog(@"validmode, Current Xposition, brickX: %d", brickX);
NSLog(@"validmode, Current Yposition, brickY: %d", brickY);
// blank spot above current brick
if( brickX == blankPosition.x && brickY == blankPosition.y+1 ){
return UP;
NSLog(@"UP");
}
// bank splot below current brick
if( brickX == blankPosition.x && brickY == blankPosition.y-1 ){
return DOWN;
NSLog(@"Down");
}
// bank spot left of the current brick
if( brickX == blankPosition.x+1 && brickY == blankPosition.y ){
return LEFT;
NSLog(@"Left");
}
// bank spot right of the current brick
if( brickX == blankPosition.x-1 && brickY == blankPosition.y ){
return RIGHT;
NSLog(@"Right");
}
return NONE;
}
//Animation of the direction of the movement
-(void) movePiece: (int) brickX YPosition: (int) brickY inDirectionX: (int) dx inDirectionY: (int) dy withAnimation: (BOOL) animate{
NSLog(@"MovePiece in Direction, Xposition, brickX: %d", brickX);
NSLog(@"MovePiece in Direction, Yposition, brickY: %d", brickY);
NSLog(@"MovePiece in Direction, inDirectionX, dx: %d", dx);
NSLog(@"MovePiece in Direction, inDirectionY, dy: %d", dy);
currentPosition = CGPointMake(brickX +dx,brickY + dy);
int Dx = currentPosition.x;
int Dy = currentPosition.y;
NSLog(@"MovePiece in Direction, CurrentPosition.x (BrickX+dx) = Dx: %d", Dx);
NSLog(@"MovePiece in Direction, CurrentPosition.y (BrickY+dy) = Dy: %d", Dy);
blankPosition = CGPointMake(blankPosition.x-dx, blankPosition.y-dy);
int Bx = blankPosition.x;
int By = blankPosition.y;
NSLog(@"MovePiece in Direction, Movedposition, blankPosition.x (blankPosition.x-dx) = Bx: %d", Bx);
NSLog(@"MovePiece in Direction, Movedposition, blankPosition.y (blankPosition.y-dy) = By: %d", By);
if( animate ){
[UIView beginAnimations:@"frame" context:nil];
}
//Moving the brick to it´s new location
grid[brickX][brickY].frame = CGRectMake((Dx * 48)+52, (Dy * 49)+7, 50, 50 );
if( animate ){
[UIView commitAnimations];
}
[sharedSoundManager playSoundWithKey:@"movingbricks" gain:0.13f pitch:1.0f shouldLoop:NO];
}
//Which direction the brick will move to
-(void) movePiece:(int) brickX YPosition: (int) brickY withAnimation:(BOOL) animate{
NSLog(@"MovePiece with Animation, Current Xposition, brickX: %d", brickX);
NSLog(@"MovePiece with Animation, Current Xposition, brickY: %d", brickY);
switch([self validMove:brickX Yposition:brickY]){
case UP:
[self movePiece: brickX YPosition: brickY inDirectionX:0 inDirectionY:-1 withAnimation:animate];
NSLog(@"UP");
NSLog(@"-----------------------------------------------");
break;
case DOWN:
[self movePiece:brickX YPosition: brickY inDirectionX:0 inDirectionY:1 withAnimation:animate];
NSLog(@"DOWN");
NSLog(@"-----------------------------------------------");
break;
case LEFT:
[self movePiece:brickX YPosition: brickY inDirectionX:-1 inDirectionY:0 withAnimation:animate];
NSLog(@"LEFT");
NSLog(@"-----------------------------------------------");
break;
case RIGHT:
[self movePiece:brickX YPosition: brickY inDirectionX:1 inDirectionY:0 withAnimation:animate];
NSLog(@"RIGHT");
NSLog(@"-----------------------------------------------");
break;
default:
break;
}
}
//Get the point on the screen (but inside the grid) where the touch was made
-(void) getPieceAtPoint:(CGPoint) point{
CGRect touchRect = CGRectMake(point.x, point.y, 1.0, 1.0);
NSLog(@"getPieceAtPoint, point.x: %d" , point.x);
NSLog(@"getPieceAtPoint, point.y: %d" , point.y);
for (int y = 0; y < BRICKHEIGHT; y++){
for (int x = 0; x < BRICKWIDTH; x++){
if( CGRectIntersectsRect([grid[x][y] frame], touchRect) ){
NSLog(@"getPieceAtPoint, Forloop, X: %d" , x);
NSLog(@"getPieceAtPoint, Forloop, Y: %d" , y);
[self movePiece:x YPosition:y withAnimation:YES];
}
}
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"touchesEnded");
if(!GamePaused){
int Bx = blankPosition.x;
int By = blankPosition.y;
NSLog(@"touchesEnded, blankPosition.x = Bx: %d", Bx);
NSLog(@"touchesEnded, blankPosition.y = By: %d", By);
int Dx = currentPosition.x;
int Dy = currentPosition.y;
NSLog(@"touchesEnded, CurrentPosition.x = Dx: %d", Dx);
NSLog(@"touchesEnded, CurrentPosition.y = Dy: %d", Dy);
UITouch *touch = [touches anyObject];
CGPoint currentTouch = [touch locationInView:self.view];
[self getPieceAtPoint:currentTouch];
}
}