Update Pong/lib/main.dart

main
Benjamin Löffler 2024-01-10 14:49:33 +01:00
parent bf51c6a614
commit 54bf6cd5d9
1 changed files with 227 additions and 27 deletions

View File

@ -1,6 +1,14 @@
import 'dart:async';
import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:pong/pong_menu.dart';
void main() { void main() {
// Run the PongGame app
runApp(const PongGame()); runApp(const PongGame());
} }
@ -10,9 +18,11 @@ class PongGame extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return MaterialApp( return MaterialApp(
// Set the app title and theme
title: 'Pong Game', title: 'Pong Game',
theme: theme: ThemeData(
ThemeData(scaffoldBackgroundColor: Color.fromARGB(255, 41, 38, 38)), scaffoldBackgroundColor: const Color.fromARGB(255, 41, 38, 38)),
// Set the initial screen to the StartScreen
home: const StartScreen(), home: const StartScreen(),
); );
} }
@ -26,6 +36,7 @@ class StartScreen extends StatelessWidget {
return Scaffold( return Scaffold(
body: GestureDetector( body: GestureDetector(
onTap: () { onTap: () {
// Navigate to the GameScreen when tapped
Navigator.of(context).push(MaterialPageRoute( Navigator.of(context).push(MaterialPageRoute(
builder: (context) { builder: (context) {
return const GameScreen(); return const GameScreen();
@ -33,9 +44,9 @@ class StartScreen extends StatelessWidget {
)); ));
}, },
child: const Center( child: const Center(
// Display a message prompting the user to touch the screen to begin
child: Text( child: Text(
'Berühren um zu beginnen!', 'Berühren um zu beginnen!',
key: Key("tapToStart"),
style: TextStyle( style: TextStyle(
fontSize: 30, fontSize: 30,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
@ -52,20 +63,155 @@ class GameScreen extends StatefulWidget {
const GameScreen({super.key}); const GameScreen({super.key});
@override @override
State<GameScreen> createState() => _GameScreenState(); State<GameScreen> createState() => GameScreenState();
} }
class _GameScreenState extends State<GameScreen> { class GameScreenState extends State<GameScreen> {
final racketWidth = 120.0; // Constants defining properties of the game
final racketHeight = 25.0; final ballSize = 20.0;
final racketWidth = 100.0;
final racketHeight = 10.0;
final racketBottomOffset = 100.0; final racketBottomOffset = 100.0;
bool isPaused = false;
double ballX = 0; // Initial speed of the ball
double ballY = 0; final initialBallSpeed = 3.0;
// Variables to track ball and racket positions, speed, score, and game state
double ballPositionX = 0;
double ballPositionY = 0;
double ballSpeedX = 0;
double ballSpeedY = 0;
double racketX = 20; double racketX = 20;
double racketY = 0; int score = 0;
moveRacket(double x) { // Ticker for updating the game state
late Ticker ticker;
double ballSpeedMultiplier = 1.1;
@override
void initState() {
super.initState();
// Initialize the game state when the widget is created
startGame();
}
// Initialize the game state
void startGame() {
final random = Random();
ballPositionX = 0;
ballPositionY = 0;
ballSpeedX = initialBallSpeed;
ballSpeedY = initialBallSpeed;
ballSpeedMultiplier = 1.1;
racketX = 200;
score = 0;
// Randomize initial ball direction
if (random.nextBool()) ballSpeedX = -ballSpeedX;
if (random.nextBool()) ballSpeedY = -ballSpeedY;
// Start the game loop after a delay
continueGame();
}
// Stop the game loop
void stopGame() {
ticker.dispose();
}
// Continue the game loop with a delay
void continueGame() {
if (!isPaused) {
Future.delayed(const Duration(seconds: 1), () {
ticker = Ticker((elapsed) {
setState(() {
moveBall(ballSpeedMultiplier);
});
});
ticker.start();
});
}
}
void moveBall(double ballSpeedMultiplier) {
// Update ball position based on speed and direction
ballPositionX += ballSpeedX * ballSpeedMultiplier;
ballPositionY += ballSpeedY * ballSpeedMultiplier;
// Get the screen size
final Size screenSize = MediaQuery.of(context).size;
// Check for collisions with horizontal walls and bounce the ball
if (ballPositionX < 0 || ballPositionX > screenSize.width - ballSize) {
ballSpeedX = -ballSpeedX;
}
// Check for collision with the top wall and bounce the ball
if (ballPositionY < 0) {
ballSpeedY = -ballSpeedY;
}
// Check if the ball has touched the floor
var ballTouchesFloor = ballPositionY > screenSize.height - ballSize;
// Check if the ball collides with the racket
var ballCollidesWithRacket =
ballPositionY + ballSize >= screenSize.height - racketBottomOffset &&
ballPositionY <= screenSize.height - racketBottomOffset &&
ballPositionX + ballSize >= racketX &&
ballPositionX <= racketX + racketWidth;
// Handle collision with the racket
if (ballCollidesWithRacket) {
// Check if the ball hits the top of the racket
if (ballPositionY <= screenSize.height - racketBottomOffset) {
ballSpeedY =
-ballSpeedY * ballSpeedMultiplier; // Bounce the ball upward
setState(() {
score += 1; // Increase the score
debugPrint('ballSpeedMultiplier: $ballSpeedMultiplier');
});
ballPositionY = screenSize.height - racketBottomOffset - ballSize;
// Adjust the Y position to stay above the racket
} else {
ballSpeedX =
-ballSpeedX * ballSpeedMultiplier; // Bounce the ball backward
// Adjust the Y position to prevent the ball from going through the racket
double adjustedY = screenSize.height - racketBottomOffset - ballSize;
if (ballPositionY < adjustedY) {
ballPositionY = adjustedY;
}
}
// Handle game over condition if the ball touches the floor
} else if (ballTouchesFloor) {
debugPrint('Game over');
stopGame();
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return PongMenu(
title: 'Game over!',
subTitle: 'Deine Punkte: $score',
child: CupertinoButton(
child: const Text('Nochmal spielen'),
onPressed: () {
Navigator.of(context).pop();
startGame();
},
),
);
},
);
}
}
void moveRacket(double x) {
// Move the racket horizontally based on the user's touch position
setState(() { setState(() {
racketX = x - racketWidth / 2; racketX = x - racketWidth / 2;
}); });
@ -74,23 +220,71 @@ class _GameScreenState extends State<GameScreen> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
body: GestureDetector( body: Stack(
children: [
GestureDetector(
// Listen for horizontal drag updates to move the racket
onHorizontalDragUpdate: (details) { onHorizontalDragUpdate: (details) {
moveRacket(details.globalPosition.dx); moveRacket(details.globalPosition.dx);
}, },
child: CustomPaint( child: CustomPaint(
key: const Key("customPaint"),
painter: PongGamePainter( painter: PongGamePainter(
racketHeight: 30, racketHeight: racketHeight,
racketWidth: 100, racketWidth: racketWidth,
racketX: racketX, racketX: racketX,
racketBottomOffset: racketBottomOffset, racketBottomOffset: racketBottomOffset,
ballSize: 20, ballSize: ballSize,
ballX: 10, ballX: ballPositionX,
ballY: 10), ballY: ballPositionY,
),
size: Size.infinite, size: Size.infinite,
), ),
), ),
Center(
// Display the player's score in the center of the screen
child: Text(
'Punkte: $score',
style: const TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold,
),
),
),
Positioned(
top: 40,
right: 20,
child: IconButton(
icon: const Icon(
CupertinoIcons.pause,
size: 30,
color: Colors.white,
),
onPressed: () {
// Pause the game and show dialog
stopGame();
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return PongMenu(
title: 'Pause',
subTitle: 'Deine Punkte: $score',
child: CupertinoButton(
onPressed: () {
// Continues the game
Navigator.of(context).pop();
isPaused = false;
continueGame();
},
child: const Text('Fortfahren'),
),
);
});
},
),
)
],
),
); );
} }
} }
@ -105,6 +299,7 @@ class PongGamePainter extends CustomPainter {
final double racketHeight; final double racketHeight;
final double racketBottomOffset; final double racketBottomOffset;
// Constructor to initialize the painter with required properties
PongGamePainter({ PongGamePainter({
required this.ballSize, required this.ballSize,
required this.ballX, required this.ballX,
@ -117,14 +312,18 @@ class PongGamePainter extends CustomPainter {
@override @override
void paint(Canvas canvas, Size size) { void paint(Canvas canvas, Size size) {
// Paint object for drawing the racket
final racketPaint = Paint()..color = Colors.white; final racketPaint = Paint()..color = Colors.white;
// Paint object for drawing the ball
final ballPaint = Paint()..color = Colors.white; final ballPaint = Paint()..color = Colors.white;
// Draw the ball as an oval on the canvas
canvas.drawOval( canvas.drawOval(
Rect.fromLTWH(ballX, ballY, ballSize, ballSize), Rect.fromLTWH(ballX, ballY, ballSize, ballSize),
ballPaint, ballPaint,
); );
// Draw the racket as a rectangle on the canvas
canvas.drawRect( canvas.drawRect(
Rect.fromLTWH( Rect.fromLTWH(
racketX, racketX,
@ -138,6 +337,7 @@ class PongGamePainter extends CustomPainter {
@override @override
bool shouldRepaint(covariant PongGamePainter oldDelegate) { bool shouldRepaint(covariant PongGamePainter oldDelegate) {
// Repaint only if the ball or racket position changes
return ballX != oldDelegate.ballX || return ballX != oldDelegate.ballX ||
ballY != oldDelegate.ballY || ballY != oldDelegate.ballY ||
racketX != oldDelegate.racketX; racketX != oldDelegate.racketX;