본문 바로가기
플러터의 기초부터 개발까지

플러터(Flutter)의 앱에서 게임 보드 구현

by 브레인TJ 2023. 5. 11.
반응형

플러터(Flutter)를 사용하여 앱에서 게임 보드를 나타내기 위해 CustomPainter 클래스를 확장하는 새 위젯을 만들 수 있습니다. 이 위젯은 플러터(Flutter)에서 제공하는 2D 드로잉 표면인 캔버스에 게임 요소를 그립니다.

게임 보드를 나타내는 새 위젯을 만드는 방법

class GameBoard extends StatelessWidget {

@override

Widget build(BuildContext context) {

return CustomPaint(

painter: BoardPainter(),

size: Size.infinite,

); } }

class BoardPainter extends CustomPainter {

@override

void paint(Canvas canvas, Size size) {

// Draw the background color of the game board.

final paint = Paint()..color = Colors.green;

canvas.drawRect(Offset.zero & size, paint);

 

// Draw the pockets on the game board.

final pocketPaint = Paint()..color = Colors.black;

final pocketRadius = 20.0;

canvas.drawCircle(Offset(pocketRadius, pocketRadius), pocketRadius, pocketPaint);

canvas.drawCircle(Offset(size.width - pocketRadius, pocketRadius), pocketRadius, pocketPaint); canvas.drawCircle(Offset(size.width - pocketRadius, size.height - pocketRadius), pocketRadius, pocketPaint); canvas.drawCircle(Offset(pocketRadius, size.height - pocketRadius), pocketRadius, pocketPaint);

 

// Draw the balls on the game board.

final ballPaint = Paint()..color = Colors.white;

final ballRadius = 10.0;

canvas.drawCircle(Offset(size.width / 2, size.height / 2), ballRadius, ballPaint);

canvas.drawCircle(Offset(size.width / 2 - 2 * ballRadius, size.height / 2), ballRadius, ballPaint); canvas.drawCircle(Offset(size.width / 2 + 2 * ballRadius, size.height / 2), ballRadius, ballPaint); canvas.drawCircle(Offset(size.width / 2 - ballRadius, size.height / 2 - ballRadius), ballRadius, ballPaint); canvas.drawCircle(Offset(size.width / 2 + ballRadius, size.height / 2 - ballRadius), ballRadius, ballPaint); canvas.drawCircle(Offset(size.width / 2 - ballRadius, size.height / 2 + ballRadius), ballRadius, ballPaint); canvas.drawCircle(Offset(size.width / 2 + ballRadius, size.height / 2 + ballRadius), ballRadius, ballPaint);

}

@override

bool shouldRepaint(covariant CustomPainter oldDelegate) {

return false;

} }

결론 :

GameBoard 위젯은 BoardPainter 클래스를 지정하는 painter 인수를 사용하는 CustomPaint 위젯을 반환합니다. BoardPainter 클래스는 paint 메서드를 오버라이드하여 게임판, 주머니, 공의 배경색을 캔버스에 그립니다. shouldRepaint 메서드는 캔버스를 다시 그리지 않아야 함을 나타내는 false를 반환합니다. 페인트 방식으로 게임 요소의 색상, 크기, 위치를 조정하여 게임 보드의 모양과 레이아웃을 사용자 지정할 수 있습니다. GameBoard 위젯을 만든 후에는 다른 위젯처럼 앱의 UI 트리에 추가할 수 있습니다.

반응형

댓글