From 149819fdd4b9dbd23d4e094fed3d40e62a070673 Mon Sep 17 00:00:00 2001 From: adithyagenie Date: Wed, 23 Nov 2022 23:33:16 +0530 Subject: [PATCH] Introducing pong and snake --- .gitignore | 3 +- credentials.pickle | Bin 169 -> 169 bytes maze/modules/PlayerBase_func.py | 2 +- maze/modules/__init__.py | 3 + maze/modules/maze.py | 26 +++-- pong.py | 193 ++++++++++++++++++++++++++++++++ snake.py | 112 ++++++++++++++++++ starter.py | 12 +- 8 files changed, 334 insertions(+), 17 deletions(-) create mode 100644 pong.py create mode 100644 snake.py diff --git a/.gitignore b/.gitignore index e2c27b0..1a3f0ca 100644 --- a/.gitignore +++ b/.gitignore @@ -4,4 +4,5 @@ PlayerBase_func.pybak __pycache__ maze/__pycache__ maze/modules/__pycache__ -saves \ No newline at end of file +saves +tetris \ No newline at end of file diff --git a/credentials.pickle b/credentials.pickle index 452764f1f782f28314866bea14aac8b148391546..093f73c6bfa8ef379e10626b444f90187ad697c5 100644 GIT binary patch delta 81 zcmZ3n>1kSfa0F9A{o ViN(b*Ua4MjA!`IkcOhG;9sord8v_6U delta 81 zcmZ3= self.y_border[1]) + or (y <= self.y_border[0] + 1) + else False + ) # Gives True if out of bound coords + checkx = ( + lambda x: True + if (x in self.x_border) + or (x >= self.x_border[1] - 1) + or (x <= self.x_border[0] + 1) + else False + ) + + actual_game_checky = ( + lambda y: True if (y <= self.y_border[0]) else False + ) # Gives true if ball at top + + to_movey = calc_to_movey(self.ball_coords[0]) # Moving here after speed alter + to_movex = calc_to_movex(self.ball_coords[1]) + old_ball = self.ball_coords.copy() + collision = False + pos = self.screen.instr(to_movey, to_movex, 1).decode("utf-8") + if pos == "=" or pos == "[" or pos == "]": + collision = True + if ( + actual_game_checky(to_movey) or collision + ): # Deflect ball if top border/collision + self.ball_dy *= -1 + elif to_movey >= self.y_border[1] and not collision: + return [None, None], [None, None], "OVER" + if checkx(to_movex): + self.ball_dx *= -1 + self.ball_coords[0] += self.ball_dy + self.ball_coords[1] += self.ball_dx + if collision: + return self.ball_coords, old_ball, "collision" + return self.ball_coords, old_ball, "nocollision" + + +class Player: + def __init__(self, y, x): + self.y = y + self.x = x + self.paddle = "[=======]" + self.paddle_posx = x // 2 + self.paddle_posy = y - 1 # Top of paddle + + def player_move(self, dir): + if dir == "LEFT" and self.paddle_posx > 1: + self.paddle_posx -= 1 + if dir == "RIGHT" and self.paddle_posx + 10 < self.x: + self.paddle_posx += 1 + return self.paddle_posy, self.paddle_posx + + +def player_movement(screen, player): + global quit + screen.keypad(True) + while 1: + # f.write("player running\n") + if quit.is_set(): + break + old_player_coordsy = player_coordsy = player.paddle_posy + old_player_coordsx = player_coordsx = player.paddle_posx + key = screen.getch() + if key == 27: + quit.set() + elif key == curses.KEY_LEFT: + player_coordsy, player_coordsx = player.player_move("LEFT") + elif key == curses.KEY_RIGHT: + player_coordsy, player_coordsx = player.player_move("RIGHT") + screen.addstr(old_player_coordsy, old_player_coordsx, " ") + screen.addstr(player_coordsy, player_coordsx, player.paddle) + + +def ball_movement(screen, ball, score): + y, x = screen.getmaxyx() + while 1: + # f.write("ball running\n") + if quit.is_set(): + break + speed_multi = score.speed_multiplier + time.sleep(speed_multi) + ball_coords = ball.move() + old_ball_posy, old_ball_posx = ball_coords[1] + ball_posy, ball_posx = ball_coords[0] + collision = ball_coords[2] + if collision == "OVER": + finalscore = score.score + screen.addstr(y // 2 - 1, x // 2 - 4, "GAME OVER!") + screen.addstr(y // 2, x // 2 - 5, "The Score is: " + str(finalscore)) + time.sleep(5) + quit.set() + break + elif collision == "collision": + score.scoreupdate() + screen.addch(old_ball_posy, old_ball_posx, " ") + screen.addch(ball_posy, ball_posx, "*") + screen.refresh() + + +def main(screen): + screen.clear() + screen.refresh() + screen.nodelay(True) + curses.curs_set(False) + screen.keypad(True) + y, x = screen.getmaxyx() + ball = Ball(y, x, screen) + score = Scores() + player = Player(y, x) + ball_thread = threading.Thread( + target=ball_movement, + args=( + screen, + ball, + score, + ), + ) + player_thread = threading.Thread( + target=player_movement, + args=( + screen, + player, + ), + ) + ball_thread.start() + player_thread.run() + # player_movement(screen, player) + + +if __name__ == "__main__": + curses.wrapper(main) diff --git a/snake.py b/snake.py new file mode 100644 index 0000000..31c796e --- /dev/null +++ b/snake.py @@ -0,0 +1,112 @@ +import curses +import random +import time +from curses import textpad + +OPPOSITE_DIRECTION_DICT = { + curses.KEY_UP: curses.KEY_DOWN, + curses.KEY_DOWN: curses.KEY_UP, + curses.KEY_RIGHT: curses.KEY_LEFT, + curses.KEY_LEFT: curses.KEY_RIGHT, +} + +DIRECTIONS_LIST = [curses.KEY_RIGHT, curses.KEY_LEFT, curses.KEY_DOWN, curses.KEY_UP] + + +def create_food(snake, box): + """Simple function to find coordinates of food which is inside box and not on snake body""" + food = None + while food is None: + food = [ + random.randint(box[0][0] + 1, box[1][0] - 1), + random.randint(box[0][1] + 1, box[1][1] - 1), + ] + if food in snake: + food = None + return food + + +def main(stdscr): + # initial settings + curses.curs_set(0) + stdscr.nodelay(1) + stdscr.timeout(100) + + # create a game box + sh, sw = stdscr.getmaxyx() + box = [[3, 3], [sh - 3, sw - 3]] # [[ul_y, ul_x], [dr_y, dr_x]] + textpad.rectangle(stdscr, box[0][0], box[0][1], box[1][0], box[1][1]) + + # create snake and set initial direction + snake = [[sh // 2, sw // 2 + 1], [sh // 2, sw // 2], [sh // 2, sw // 2 - 1]] + direction = curses.KEY_RIGHT + + # draw snake + for y, x in snake: + stdscr.addstr(y, x, "#") + + # create food + food = create_food(snake, box) + stdscr.addstr(food[0], food[1], "*") + + # print score + score = 0 + score_text = "Score: {}".format(score) + stdscr.addstr(1, sw // 2 - len(score_text) // 2, score_text) + + while 1: + # non-blocking input + key = stdscr.getch() + + # set direction if user pressed any arrow key and that key is not opposite of current direction + if key in DIRECTIONS_LIST and key != OPPOSITE_DIRECTION_DICT[direction]: + direction = key + + # find next position of snake head + head = snake[0] + if direction == curses.KEY_RIGHT: + new_head = [head[0], head[1] + 1] + elif direction == curses.KEY_LEFT: + new_head = [head[0], head[1] - 1] + elif direction == curses.KEY_DOWN: + new_head = [head[0] + 1, head[1]] + elif direction == curses.KEY_UP: + new_head = [head[0] - 1, head[1]] + + # insert and print new head + stdscr.addstr(new_head[0], new_head[1], "#") + snake.insert(0, new_head) + + # if sanke head is on food + if snake[0] == food: + # update score + score += 1 + score_text = "Score: {}".format(score) + stdscr.addstr(1, sw // 2 - len(score_text) // 2, score_text) + + # create new food + food = create_food(snake, box) + stdscr.addstr(food[0], food[1], "*") + + # increase speed of game + stdscr.timeout(100 - (len(snake) // 3) % 90) + else: + # shift snake's tail + stdscr.addstr(snake[-1][0], snake[-1][1], " ") + snake.pop() + + # conditions for game over + if ( + snake[0][0] in [box[0][0], box[1][0]] + or snake[0][1] in [box[0][1], box[1][1]] + or snake[0] in snake[1:] + ): + msg = "Game Over!" + stdscr.addstr(sh // 2, sw // 2 - len(msg) // 2, msg) + stdscr.nodelay(0) + stdscr.getch() + time.sleep(5) + break + + +curses.wrapper(main) diff --git a/starter.py b/starter.py index 285a485..94f1a4d 100644 --- a/starter.py +++ b/starter.py @@ -16,7 +16,7 @@ with open("credentials.pickle", "rb") as f: user = d["user"] password = d["pass"] break - except EOFError: + except: user = password = None @@ -38,7 +38,7 @@ Run 'python starter.py initsql' to initialise credentials of your choice. """ d["pass"] = "" f.seek(pos) pickle.dump(d, f) - except EOFError: + except: pass return None, None @@ -53,9 +53,9 @@ else: databaseinit() subprocess.call( f"mysql -u {user} --password={password} -D labyrinth < {os.path.abspath('dbdump.sql')}", - shell=True#, - #stdout=subprocess.DEVNULL, - #stderr=subprocess.DEVNULL, + shell=True # , + # stdout=subprocess.DEVNULL, + # stderr=subprocess.DEVNULL, ) print("Successfully dumped sample data") elif sys.argv[1] == "initsql": @@ -71,6 +71,6 @@ else: d["pass"] = password f.seek(pos) pickle.dump(d, f) - except EOFError: + except: pass print("Successfully set.")