Fixed snake going into the border

Bugs: I think the food might spawn into the border making the game unplayable.
Fixed: The snake can no longer go inside the border.
Also fixed the bug where pressing a key multiple times could skip the
food while the snake went over it.
This commit is contained in:
Uttarayan Mondal
2021-01-18 23:55:57 +05:30
parent cad605c458
commit 477ffdb036
3 changed files with 18 additions and 11 deletions
+4 -4
View File
@@ -125,10 +125,10 @@ impl Board {
}
pub fn check_collision(&mut self, snake: &Snake) -> bool {
let (snake_line, snake_col): (i32, i32) = snake.posyx();
if (snake_line >= self.maxlines)
|| (snake_col >= self.maxcols)
|| (snake_line < 0)
|| (snake_col < 0)
if (snake_line >= self.maxlines - 1)
|| (snake_col >= self.maxcols - 1)
|| (snake_line <= 0)
|| (snake_col <= 0)
{
self.gamestate = GameState::Failed(FailState::Wall);
return true;
+12 -4
View File
@@ -1,8 +1,7 @@
// use ncurses::*;
use crate::game::backend::{Board, Snake};
use ncurses::{
box_, delwin, keypad, mvwaddstr, newwin, stdscr, waddstr, wborder, wclrtobot, wmove, wrefresh,
WINDOW,
box_, delwin, keypad, mvwaddstr, newwin, stdscr, wborder, wclrtobot, wmove, wrefresh, WINDOW,
};
pub fn game_window(mlines: i32, mcols: i32, vmargin: i32, hmargin: i32) -> WINDOW {
let game_win: WINDOW;
@@ -46,12 +45,21 @@ pub fn draw_board(board: &Board, game_win: WINDOW) {
mvwaddstr(game_win, food_l, food_c, "F");
}
pub fn log(snake: &Snake, board: &Board) {
pub fn _log(snake: &Snake, board: &Board) {
let (shl, shc): (i32, i32) = snake.posyx();
let (bfl, bfc): (i32, i32) = board.food_posyx();
mvwaddstr(stdscr(), 0, 0, &format!("snake:head: {} {} ", shl, shc));
mvwaddstr(stdscr(), 1, 0, &format!("board:food: {} {} ", bfl, bfc));
wmove(stdscr(), 2, 0);
// mvwaddstr(
// stdscr(),
// 2,
// 0,
// &format!(
// "board:maxlines {} maxcols {}",
// board.maxlines, board.maxcols
// ),
// );
// for snake_cell in snake.iter() {
// let (scl, scc): (i32, i32) = snake_cell.posyx();
// waddstr(stdscr(), &format!("cell: {} {} ", scl, scc));
+2 -3
View File
@@ -19,7 +19,7 @@ pub fn start() {
loop {
frontend::draw_snake(&snake, game_win);
frontend::draw_board(&board, game_win);
frontend::log(&snake, &board);
// frontend::_log(&snake, &board);
if board.check_collision(&snake) {
break;
}
@@ -50,9 +50,8 @@ pub fn start() {
nodelay(game_win, true);
}
// 27 => break,
_ => (),
_ => snake.tick(std::time::Duration::from_millis(100)),
}
snake.tick(std::time::Duration::from_millis(100));
}
frontend::destroy_window(game_win);