From 74185830511e8718ce72bd30d6cd86290a887ff7 Mon Sep 17 00:00:00 2001 From: Kumar Aditya <17bcs031@smvdu.ac.in> Date: Thu, 14 May 2020 11:49:22 +0530 Subject: [PATCH 1/2] Create tetris.py --- Code/tetris.py | 396 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 396 insertions(+) create mode 100644 Code/tetris.py diff --git a/Code/tetris.py b/Code/tetris.py new file mode 100644 index 0000000..175bf85 --- /dev/null +++ b/Code/tetris.py @@ -0,0 +1,396 @@ +import pygame +import random + +""" +10 x 20 square grid +shapes: S, Z, I, O, J, L, T +represented in order by 0 - 6 +""" + +pygame.font.init() + +# GLOBALS VARS +s_width = 800 +s_height = 700 +play_width = 300 # meaning 300 // 10 = 30 width per block +play_height = 600 # meaning 600 // 20 = 20 height per blo ck +block_size = 30 + +top_left_x = (s_width - play_width) // 2 +top_left_y = s_height - play_height + + +# SHAPE FORMATS + +S = [['.....', + '.....', + '..00.', + '.00..', + '.....'], + ['.....', + '..0..', + '..00.', + '...0.', + '.....']] + +Z = [['.....', + '.....', + '.00..', + '..00.', + '.....'], + ['.....', + '..0..', + '.00..', + '.0...', + '.....']] + +I = [['..0..', + '..0..', + '..0..', + '..0..', + '.....'], + ['.....', + '0000.', + '.....', + '.....', + '.....']] + +O = [['.....', + '.....', + '.00..', + '.00..', + '.....']] + +J = [['.....', + '.0...', + '.000.', + '.....', + '.....'], + ['.....', + '..00.', + '..0..', + '..0..', + '.....'], + ['.....', + '.....', + '.000.', + '...0.', + '.....'], + ['.....', + '..0..', + '..0..', + '.00..', + '.....']] + +L = [['.....', + '...0.', + '.000.', + '.....', + '.....'], + ['.....', + '..0..', + '..0..', + '..00.', + '.....'], + ['.....', + '.....', + '.000.', + '.0...', + '.....'], + ['.....', + '.00..', + '..0..', + '..0..', + '.....']] + +T = [['.....', + '..0..', + '.000.', + '.....', + '.....'], + ['.....', + '..0..', + '..00.', + '..0..', + '.....'], + ['.....', + '.....', + '.000.', + '..0..', + '.....'], + ['.....', + '..0..', + '.00..', + '..0..', + '.....']] + +shapes = [S, Z, I, O, J, L, T] +shape_colors = [(0, 255, 0), (255, 0, 0), (0, 255, 255), (255, 255, 0), (255, 165, 0), (0, 0, 255), (128, 0, 128)] +# index 0 - 6 represent shape + + +class Piece(object): + rows = 20 # y + columns = 10 # x + + def __init__(self, column, row, shape): + self.x = column + self.y = row + self.shape = shape + self.color = shape_colors[shapes.index(shape)] + self.rotation = 0 # number from 0-3 + + +def create_grid(locked_positions={}): + grid = [[(0,0,0) for x in range(10)] for x in range(20)] + + for i in range(len(grid)): + for j in range(len(grid[i])): + if (j,i) in locked_positions: + c = locked_positions[(j,i)] + grid[i][j] = c + return grid + + +def convert_shape_format(shape): + positions = [] + format = shape.shape[shape.rotation % len(shape.shape)] + + for i, line in enumerate(format): + row = list(line) + for j, column in enumerate(row): + if column == '0': + positions.append((shape.x + j, shape.y + i)) + + for i, pos in enumerate(positions): + positions[i] = (pos[0] - 2, pos[1] - 4) + + return positions + + +def valid_space(shape, grid): + accepted_positions = [[(j, i) for j in range(10) if grid[i][j] == (0,0,0)] for i in range(20)] + accepted_positions = [j for sub in accepted_positions for j in sub] + formatted = convert_shape_format(shape) + + for pos in formatted: + if pos not in accepted_positions: + if pos[1] > -1: + return False + + return True + + +def check_lost(positions): + for pos in positions: + x, y = pos + if y < 1: + return True + return False + + +def get_shape(): + global shapes, shape_colors + + return Piece(5, 0, random.choice(shapes)) + + +def draw_text_middle(text, size, color, surface): + font = pygame.font.SysFont('comicsans', size, bold=True) + label = font.render(text, 1, color) + + surface.blit(label, (top_left_x + play_width/2 - (label.get_width() / 2), top_left_y + play_height/2 - label.get_height()/2)) + + +def draw_grid(surface, row, col): + sx = top_left_x + sy = top_left_y + for i in range(row): + pygame.draw.line(surface, (128,128,128), (sx, sy+ i*30), (sx + play_width, sy + i * 30)) # horizontal lines + for j in range(col): + pygame.draw.line(surface, (128,128,128), (sx + j * 30, sy), (sx + j * 30, sy + play_height)) # vertical lines + + +def clear_rows(grid, locked): + # need to see if row is clear the shift every other row above down one + + inc = 0 + for i in range(len(grid)-1,-1,-1): + row = grid[i] + if (0, 0, 0) not in row: + inc += 1 + # add positions to remove from locked + ind = i + for j in range(len(row)): + try: + del locked[(j, i)] + except: + continue + if inc > 0: + for key in sorted(list(locked), key=lambda x: x[1])[::-1]: + x, y = key + if y < ind: + newKey = (x, y + inc) + locked[newKey] = locked.pop(key) + + +def draw_next_shape(shape, surface): + font = pygame.font.SysFont('comicsans', 30) + label = font.render('Next Shape', 1, (255,255,255)) + + sx = top_left_x + play_width + 50 + sy = top_left_y + play_height/2 - 100 + format = shape.shape[shape.rotation % len(shape.shape)] + + for i, line in enumerate(format): + row = list(line) + for j, column in enumerate(row): + if column == '0': + pygame.draw.rect(surface, shape.color, (sx + j*30, sy + i*30, 30, 30), 0) + + surface.blit(label, (sx + 10, sy- 30)) + + +def draw_window(surface): + surface.fill((0,0,0)) + # Tetris Title + font = pygame.font.SysFont('comicsans', 60) + label = font.render('TETRIS', 1, (255,255,255)) + + surface.blit(label, (top_left_x + play_width / 2 - (label.get_width() / 2), 30)) + + for i in range(len(grid)): + for j in range(len(grid[i])): + pygame.draw.rect(surface, grid[i][j], (top_left_x + j* 30, top_left_y + i * 30, 30, 30), 0) + + # draw grid and border + draw_grid(surface, 20, 10) + pygame.draw.rect(surface, (255, 0, 0), (top_left_x, top_left_y, play_width, play_height), 5) + # pygame.display.update() + + +def main(): + global grid + + locked_positions = {} # (x,y):(255,0,0) + grid = create_grid(locked_positions) + + change_piece = False + run = True + current_piece = get_shape() + next_piece = get_shape() + clock = pygame.time.Clock() + fall_time = 0 + level_time = 0 + fall_speed = 0.27 + score = 0 + + while run: + + grid = create_grid(locked_positions) + fall_time += clock.get_rawtime() + level_time += clock.get_rawtime() + clock.tick() + + if level_time/1000 > 4: + level_time = 0 + if fall_speed > 0.15: + fall_speed -= 0.005 + + + # PIECE FALLING CODE + if fall_time/1000 >= fall_speed: + fall_time = 0 + current_piece.y += 1 + if not (valid_space(current_piece, grid)) and current_piece.y > 0: + current_piece.y -= 1 + change_piece = True + + for event in pygame.event.get(): + if event.type == pygame.QUIT: + run = False + pygame.display.quit() + quit() + + if event.type == pygame.KEYDOWN: + if event.key == pygame.K_LEFT: + current_piece.x -= 1 + if not valid_space(current_piece, grid): + current_piece.x += 1 + + elif event.key == pygame.K_RIGHT: + current_piece.x += 1 + if not valid_space(current_piece, grid): + current_piece.x -= 1 + elif event.key == pygame.K_UP: + # rotate shape + current_piece.rotation = current_piece.rotation + 1 % len(current_piece.shape) + if not valid_space(current_piece, grid): + current_piece.rotation = current_piece.rotation - 1 % len(current_piece.shape) + + if event.key == pygame.K_DOWN: + # move shape down + current_piece.y += 1 + if not valid_space(current_piece, grid): + current_piece.y -= 1 + + '''if event.key == pygame.K_SPACE: + while valid_space(current_piece, grid): + current_piece.y += 1 + current_piece.y -= 1 + print(convert_shape_format(current_piece))''' # todo fix + + shape_pos = convert_shape_format(current_piece) + + # add piece to the grid for drawing + for i in range(len(shape_pos)): + x, y = shape_pos[i] + if y > -1: + grid[y][x] = current_piece.color + + # IF PIECE HIT GROUND + if change_piece: + for pos in shape_pos: + p = (pos[0], pos[1]) + locked_positions[p] = current_piece.color + current_piece = next_piece + next_piece = get_shape() + change_piece = False + + # call four times to check for multiple clear rows + if clear_rows(grid, locked_positions): + score += 10 + + draw_window(win) + draw_next_shape(next_piece, win) + pygame.display.update() + + # Check if user lost + if check_lost(locked_positions): + run = False + + draw_text_middle("You Lost", 40, (255,255,255), win) + pygame.display.update() + pygame.time.delay(2000) + + +def main_menu(): + run = True + while run: + win.fill((0,0,0)) + draw_text_middle('Press any key to begin.', 60, (255, 255, 255), win) + pygame.display.update() + for event in pygame.event.get(): + if event.type == pygame.QUIT: + run = False + + if event.type == pygame.KEYDOWN: + main() + pygame.quit() + + +win = pygame.display.set_mode((s_width, s_height)) +pygame.display.set_caption('Tetris') + +main_menu() # start game + From f1d2221c2df300b42186823910ff0256a110526e Mon Sep 17 00:00:00 2001 From: Kumar Aditya <17bcs031@smvdu.ac.in> Date: Thu, 14 May 2020 11:57:13 +0530 Subject: [PATCH 2/2] Create snake.py --- Code/snake.py | 196 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 196 insertions(+) create mode 100644 Code/snake.py diff --git a/Code/snake.py b/Code/snake.py new file mode 100644 index 0000000..31092d3 --- /dev/null +++ b/Code/snake.py @@ -0,0 +1,196 @@ +import math +import random +import pygame +import random +import tkinter as tk +from tkinter import messagebox + +width = 500 +height = 500 + +cols = 25 +rows = 20 + + +class cube(): + rows = 20 + w = 500 + def __init__(self, start, dirnx=1, dirny=0, color=(255,0,0)): + self.pos = start + self.dirnx = dirnx + self.dirny = dirny # "L", "R", "U", "D" + self.color = color + + def move(self, dirnx, dirny): + self.dirnx = dirnx + self.dirny = dirny + self.pos = (self.pos[0] + self.dirnx, self.pos[1] + self.dirny) + + + def draw(self, surface, eyes=False): + dis = self.w // self.rows + i = self.pos[0] + j = self.pos[1] + + pygame.draw.rect(surface, self.color, (i*dis+1,j*dis+1,dis-2,dis-2)) + if eyes: + centre = dis//2 + radius = 3 + circleMiddle = (i*dis+centre-radius,j*dis+8) + circleMiddle2 = (i*dis + dis -radius*2, j*dis+8) + pygame.draw.circle(surface, (0,0,0), circleMiddle, radius) + pygame.draw.circle(surface, (0,0,0), circleMiddle2, radius) + + + +class snake(): + body = [] + turns = {} + + def __init__(self, color, pos): + #pos is given as coordinates on the grid ex (1,5) + self.color = color + self.head = cube(pos) + self.body.append(self.head) + self.dirnx = 0 + self.dirny = 1 + + def move(self): + for event in pygame.event.get(): + if event.type == pygame.QUIT: + pygame.quit() + keys = pygame.key.get_pressed() + + for key in keys: + if keys[pygame.K_LEFT]: + self.dirnx = -1 + self.dirny = 0 + self.turns[self.head.pos[:]] = [self.dirnx,self.dirny] + elif keys[pygame.K_RIGHT]: + self.dirnx = 1 + self.dirny = 0 + self.turns[self.head.pos[:]] = [self.dirnx,self.dirny] + elif keys[pygame.K_UP]: + self.dirny = -1 + self.dirnx = 0 + self.turns[self.head.pos[:]] = [self.dirnx,self.dirny] + elif keys[pygame.K_DOWN]: + self.dirny = 1 + self.dirnx = 0 + self.turns[self.head.pos[:]] = [self.dirnx,self.dirny] + + for i, c in enumerate(self.body): + p = c.pos[:] + if p in self.turns: + turn = self.turns[p] + c.move(turn[0], turn[1]) + if i == len(self.body)-1: + self.turns.pop(p) + else: + c.move(c.dirnx,c.dirny) + + + def reset(self,pos): + self.head = cube(pos) + self.body = [] + self.body.append(self.head) + self.turns = {} + self.dirnx = 0 + self.dirny = 1 + + def addCube(self): + tail = self.body[-1] + dx, dy = tail.dirnx, tail.dirny + + if dx == 1 and dy == 0: + self.body.append(cube((tail.pos[0]-1,tail.pos[1]))) + elif dx == -1 and dy == 0: + self.body.append(cube((tail.pos[0]+1,tail.pos[1]))) + elif dx == 0 and dy == 1: + self.body.append(cube((tail.pos[0],tail.pos[1]-1))) + elif dx == 0 and dy == -1: + self.body.append(cube((tail.pos[0],tail.pos[1]+1))) + + self.body[-1].dirnx = dx + self.body[-1].dirny = dy + + def draw(self, surface): + for i,c in enumerate(self.body): + if i == 0: + c.draw(surface, True) + else: + c.draw(surface) + + + +def redrawWindow(): + global win + win.fill((0,0,0)) + drawGrid(width, rows, win) + s.draw(win) + snack.draw(win) + pygame.display.update() + pass + + + +def drawGrid(w, rows, surface): + sizeBtwn = w // rows + + x = 0 + y = 0 + for l in range(rows): + x = x + sizeBtwn + y = y +sizeBtwn + + pygame.draw.line(surface, (255,255,255), (x, 0),(x,w)) + pygame.draw.line(surface, (255,255,255), (0, y),(w,y)) + + + +def randomSnack(rows, item): + positions = item.body + + while True: + x = random.randrange(1,rows-1) + y = random.randrange(1,rows-1) + if len(list(filter(lambda z:z.pos == (x,y), positions))) > 0: + continue + else: + break + + return (x,y) + + +def main(): + global s, snack, win + win = pygame.display.set_mode((width,height)) + s = snake((255,0,0), (10,10)) + s.addCube() + snack = cube(randomSnack(rows,s), color=(0,255,0)) + flag = True + clock = pygame.time.Clock() + + while flag: + pygame.time.delay(50) + clock.tick(10) + s.move() + headPos = s.head.pos + if headPos[0] >= 20 or headPos[0] < 0 or headPos[1] >= 20 or headPos[1] < 0: + print("Score:", len(s.body)) + s.reset((10, 10)) + + if s.body[0].pos == snack.pos: + s.addCube() + snack = cube(randomSnack(rows,s), color=(0,255,0)) + + for x in range(len(s.body)): + if s.body[x].pos in list(map(lambda z:z.pos,s.body[x+1:])): + print("Score:", len(s.body)) + s.reset((10,10)) + break + + redrawWindow() + +main() +