362 lines
11 KiB
Rust
362 lines
11 KiB
Rust
use crossterm::event::{Event, EventStream, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
|
|
use futures::{FutureExt, StreamExt};
|
|
use ratatui::layout::Alignment;
|
|
use ratatui::layout::Constraint::Percentage;
|
|
use ratatui::layout::HorizontalAlignment::Center;
|
|
use ratatui::style::Stylize;
|
|
use ratatui::symbols::Marker;
|
|
use ratatui::widgets::canvas::{Canvas, Line, Points, Rectangle};
|
|
use ratatui::widgets::{Clear, Paragraph};
|
|
use ratatui::{
|
|
DefaultTerminal, Frame,
|
|
layout::{Constraint, Direction, Layout},
|
|
widgets::Block,
|
|
};
|
|
use tokio::time::{Duration, interval};
|
|
|
|
// Constants
|
|
const X_BOUNDS: (f64, f64) = (0.0, 50.0);
|
|
const Y_BOUNDS: (f64, f64) = (0.0, 15.0);
|
|
const PLAYER_X: f64 = X_BOUNDS.0;
|
|
const ENEMY_X: f64 = X_BOUNDS.1 - 1.0;
|
|
const PADDLE_Y: f64 = Y_BOUNDS.1 / 2.0;
|
|
|
|
#[tokio::main]
|
|
async fn main() -> color_eyre::Result<()> {
|
|
color_eyre::install()?;
|
|
let terminal = ratatui::init();
|
|
let result = App::new().run(terminal).await;
|
|
ratatui::restore();
|
|
result
|
|
}
|
|
|
|
#[derive(Debug, Default)]
|
|
enum Gamestate {
|
|
#[default]
|
|
Playing,
|
|
Paused,
|
|
Won,
|
|
Lost,
|
|
}
|
|
|
|
#[derive(Debug, Default)]
|
|
pub struct Paddle {
|
|
x: f64,
|
|
y: f64,
|
|
}
|
|
|
|
impl Paddle {
|
|
pub fn new(x: f64, y: f64) -> Self {
|
|
Paddle { x: x, y: y }
|
|
}
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
pub struct Ball {
|
|
x: f64,
|
|
y: f64,
|
|
x_velocity: f64,
|
|
y_velocity: f64,
|
|
}
|
|
|
|
impl Default for Ball {
|
|
fn default() -> Self {
|
|
Ball {
|
|
x: X_BOUNDS.1 - 1.5,
|
|
y: PADDLE_Y + 2.0,
|
|
x_velocity: 0.5,
|
|
y_velocity: 0.5,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Ball {
|
|
pub fn update(&mut self) {
|
|
self.x += self.x_velocity;
|
|
self.y += self.y_velocity;
|
|
}
|
|
|
|
pub fn reset(&mut self, paddle: &Paddle, toward_enemy: bool) {
|
|
// Player scored = true
|
|
// Enemy scored = false
|
|
|
|
if toward_enemy == true {
|
|
self.x = paddle.x + 2.0;
|
|
self.y = paddle.y + 2.0;
|
|
self.x_velocity = 0.5;
|
|
self.y_velocity = 0.5;
|
|
} else {
|
|
self.x = paddle.x - 1.5;
|
|
self.y = paddle.y + 2.0;
|
|
self.x_velocity = -0.5;
|
|
self.y_velocity = 0.5;
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Default)]
|
|
pub struct App {
|
|
running: bool,
|
|
event_stream: EventStream,
|
|
player: Paddle,
|
|
player_score: i32,
|
|
enemy_score: i32,
|
|
enemy: Paddle,
|
|
ball: Ball,
|
|
state: Gamestate,
|
|
}
|
|
|
|
impl App {
|
|
pub fn new() -> Self {
|
|
App {
|
|
running: true,
|
|
event_stream: EventStream::new(),
|
|
player: Paddle::new(PLAYER_X, PADDLE_Y),
|
|
enemy: Paddle::new(ENEMY_X, PADDLE_Y),
|
|
ball: Ball::default(),
|
|
state: Gamestate::Playing,
|
|
player_score: 0,
|
|
enemy_score: 0,
|
|
}
|
|
}
|
|
|
|
pub fn restart(&mut self) {
|
|
self.player_score = 0;
|
|
self.enemy_score = 0;
|
|
self.state = Gamestate::Playing;
|
|
|
|
self.player = Paddle::new(PLAYER_X, PADDLE_Y);
|
|
self.enemy = Paddle::new(ENEMY_X, PADDLE_Y);
|
|
self.ball = Ball::default();
|
|
}
|
|
|
|
pub fn update(&mut self) {
|
|
match self.state {
|
|
Gamestate::Playing => {
|
|
self.ball.update();
|
|
self.update_enemy();
|
|
self.check_collisions();
|
|
self.check_state();
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
pub fn check_state(&mut self) {
|
|
if self.player_score >= 5 {
|
|
self.state = Gamestate::Won;
|
|
} else if self.enemy_score >= 5 {
|
|
self.state = Gamestate::Lost;
|
|
}
|
|
}
|
|
|
|
pub fn update_enemy(&mut self) {
|
|
let enemy_center = self.enemy.y + 2.0;
|
|
|
|
if self.ball.y > enemy_center {
|
|
if self.enemy.y + 4.0 < Y_BOUNDS.1 {
|
|
self.enemy.y += 0.25;
|
|
}
|
|
} else if self.ball.y < enemy_center {
|
|
if self.enemy.y > Y_BOUNDS.0 {
|
|
self.enemy.y -= 0.25;
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn check_collisions(&mut self) {
|
|
// Top/bottom walls
|
|
if self.ball.y <= Y_BOUNDS.0 || self.ball.y >= Y_BOUNDS.1 {
|
|
self.ball.y_velocity *= -1.0;
|
|
}
|
|
|
|
if self.ball.x >= X_BOUNDS.1 {
|
|
self.player_score += 1;
|
|
self.ball.reset(&self.player, true);
|
|
return;
|
|
}
|
|
|
|
if self.ball.x <= X_BOUNDS.0 {
|
|
self.enemy_score += 1;
|
|
self.ball.reset(&self.enemy, false);
|
|
return;
|
|
}
|
|
|
|
// Player paddle
|
|
if self.ball.x <= self.player.x + 1.0
|
|
&& self.ball.y >= self.player.y
|
|
&& self.ball.y <= self.player.y + 4.0
|
|
&& self.ball.x_velocity < 0.0
|
|
{
|
|
self.ball.x_velocity *= -1.0;
|
|
}
|
|
|
|
// Enemy paddle
|
|
if self.ball.x >= self.enemy.x - 1.0
|
|
&& self.ball.y >= self.enemy.y
|
|
&& self.ball.y <= self.enemy.y + 4.0
|
|
&& self.ball.x_velocity > 0.0
|
|
{
|
|
self.ball.x_velocity *= -1.0;
|
|
}
|
|
}
|
|
|
|
pub async fn run(mut self, mut terminal: DefaultTerminal) -> color_eyre::Result<()> {
|
|
self.running = true;
|
|
|
|
let mut interval = interval(Duration::from_millis(50));
|
|
|
|
while self.running {
|
|
terminal.draw(|frame| self.draw(frame))?;
|
|
|
|
tokio::select! {
|
|
_ = interval.tick() => {
|
|
self.update();
|
|
}
|
|
|
|
_ = self.handle_crossterm_events() => {}
|
|
}
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
fn draw(&mut self, frame: &mut Frame) {
|
|
let window = Layout::default()
|
|
.direction(Direction::Horizontal)
|
|
.constraints([Constraint::Percentage(100)])
|
|
.split(frame.area());
|
|
|
|
let popup_block = Block::new();
|
|
let centered_area = window[0].centered(Percentage(60), Percentage(20));
|
|
|
|
match self.state {
|
|
Gamestate::Playing => {
|
|
let canvas = Canvas::default()
|
|
.block(
|
|
Block::bordered()
|
|
.title(format!(
|
|
" PongRS | {} - {} ",
|
|
self.player_score, self.enemy_score
|
|
))
|
|
.title_alignment(Alignment::Center),
|
|
)
|
|
.x_bounds([X_BOUNDS.0, X_BOUNDS.1])
|
|
.y_bounds([Y_BOUNDS.0, Y_BOUNDS.1])
|
|
.marker(Marker::Block)
|
|
.paint(|ctx| {
|
|
ctx.draw(&Points {
|
|
coords: &[(self.ball.x, self.ball.y)],
|
|
color: ratatui::style::Color::Yellow,
|
|
});
|
|
ctx.draw(&Rectangle {
|
|
x: self.player.x,
|
|
y: self.player.y,
|
|
width: 1.0,
|
|
height: 4.0,
|
|
color: ratatui::style::Color::Green,
|
|
});
|
|
ctx.draw(&Rectangle {
|
|
x: self.enemy.x,
|
|
y: self.enemy.y,
|
|
width: 1.0,
|
|
height: 4.0,
|
|
color: ratatui::style::Color::Red,
|
|
});
|
|
});
|
|
|
|
let net = Canvas::default()
|
|
.x_bounds([X_BOUNDS.0, X_BOUNDS.1])
|
|
.y_bounds([Y_BOUNDS.0, Y_BOUNDS.1])
|
|
.marker(Marker::Dot)
|
|
.paint(|ctx| {
|
|
ctx.draw(&Line {
|
|
x1: X_BOUNDS.1 / 2.0,
|
|
y1: Y_BOUNDS.1 - 0.5,
|
|
x2: X_BOUNDS.1 / 2.0,
|
|
y2: Y_BOUNDS.0 + 0.5,
|
|
color: ratatui::style::Color::White,
|
|
});
|
|
});
|
|
|
|
frame.render_widget(canvas, window[0]);
|
|
frame.render_widget(net, window[0]);
|
|
}
|
|
Gamestate::Paused => {
|
|
frame.render_widget(Clear, centered_area);
|
|
let pause_message = Paragraph::new(format!(
|
|
"Paused\nScore: {} - {}",
|
|
self.player_score, self.enemy_score
|
|
))
|
|
.block(popup_block.clone())
|
|
.alignment(Center);
|
|
frame.render_widget(pause_message, centered_area);
|
|
}
|
|
Gamestate::Won => {
|
|
frame.render_widget(Clear, centered_area);
|
|
let win_message = Paragraph::new("You win!".green())
|
|
.block(popup_block)
|
|
.alignment(Center);
|
|
frame.render_widget(win_message, centered_area);
|
|
}
|
|
Gamestate::Lost => {
|
|
frame.render_widget(Clear, centered_area);
|
|
let lose_message = Paragraph::new("You lose!".red())
|
|
.block(popup_block)
|
|
.alignment(Center);
|
|
frame.render_widget(lose_message, centered_area);
|
|
}
|
|
}
|
|
}
|
|
|
|
async fn handle_crossterm_events(&mut self) -> color_eyre::Result<()> {
|
|
let event = self.event_stream.next().fuse().await;
|
|
match event {
|
|
Some(Ok(evt)) => match evt {
|
|
Event::Key(key) if key.kind == KeyEventKind::Press => self.on_key_event(key),
|
|
Event::Mouse(_) => {}
|
|
Event::Resize(_, _) => {}
|
|
_ => {}
|
|
},
|
|
_ => {}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn on_key_event(&mut self, key: KeyEvent) {
|
|
match (key.modifiers, key.code) {
|
|
(_, KeyCode::Char('q')) | (KeyModifiers::CONTROL, KeyCode::Char('c')) => self.quit(),
|
|
(_, KeyCode::Up | KeyCode::Char('k') | KeyCode::Char('w')) => self.move_up(),
|
|
(_, KeyCode::Down | KeyCode::Char('j') | KeyCode::Char('s')) => self.move_down(),
|
|
(_, KeyCode::Esc) => match self.state {
|
|
Gamestate::Playing => self.state = Gamestate::Paused,
|
|
Gamestate::Paused => self.state = Gamestate::Playing,
|
|
Gamestate::Won => self.restart(),
|
|
Gamestate::Lost => self.restart(),
|
|
},
|
|
(_, KeyCode::Char('r')) => self.restart(),
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
pub fn move_up(&mut self) {
|
|
let new_position = self.player.y + 1.0;
|
|
if new_position + 3.0 < Y_BOUNDS.1 {
|
|
self.player.y = new_position;
|
|
}
|
|
}
|
|
|
|
pub fn move_down(&mut self) {
|
|
let new_position = self.player.y - 1.0;
|
|
if new_position > Y_BOUNDS.0 {
|
|
self.player.y = new_position;
|
|
} else {
|
|
self.player.y = Y_BOUNDS.0;
|
|
}
|
|
}
|
|
|
|
fn quit(&mut self) {
|
|
self.running = false;
|
|
}
|
|
}
|