Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updated main.py #129

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added __pycache__/box.cpython-312.pyc
Binary file not shown.
305 changes: 76 additions & 229 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,29 @@
import pygame
import sys

# Constants
SCREEN_WIDTH, SCREEN_HEIGHT = 300, 300
# Constants defining various properties of the game window and cells
SCREEN_SIZE = SCREEN_WIDTH, SCREEN_HEIGHT = 300, 350 # Increased height to accommodate buttons
CELL_SIZE = 40
PADDING = 20
ROWS = COLS = (SCREEN_WIDTH - 4 * PADDING) // CELL_SIZE

# Colors
# Initialize pygame
pygame.init()
win = pygame.display.set_mode(SCREEN_SIZE)
pygame.display.set_caption("Dot and Line")
font = pygame.font.SysFont('cursive', 25)

WHITE = (255, 255, 255)
RED = (252, 91, 122)
BLUE = (78, 193, 246)
GREEN = (0, 255, 0)
BLACK = (12, 12, 12)
DARK_GRAY = (30, 30, 30)
LIGHT_GRAY = (100, 100, 100)


# Initialize Pygame
pygame.init()

screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Pygame Game with Replay and Quit")

win = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
font = pygame.font.SysFont('cursive', 25)
GREEN = (0, 255, 0)

#buttons
button_width = 200
button_height = 50
# Define button dimensions and colors
BUTTON_WIDTH = 150
BUTTON_HEIGHT = 40
BUTTON_PADDING = 10
BUTTON_COLOR = (100, 100, 100)
BUTTON_TEXT_COLOR = WHITE

# Define the Cell class to represent each cell in the grid
class Cell:
Expand All @@ -45,236 +40,88 @@ def __init__(self, row, col):
[(self.rect.right, self.rect.bottom), (self.rect.left, self.rect.bottom)],
[(self.rect.left, self.rect.bottom), (self.rect.left, self.rect.top)]
]
self.sides = [False] * 4
self.sides = [False, False, False, False]
self.winner = None

def check_win(self, winner):
if not self.winner and all(self.sides):
self.winner = winner
self.color = GREEN if winner == 'X' else RED
self.text = font.render(self.winner, True, WHITE)
return 1
if not self.winner:
if self.sides == [True] * 4:
self.winner = winner
return 1
return 0

def update(self, win):
def update(self, surface):
if self.winner:
pygame.draw.rect(win, self.color, self.rect)
win.blit(self.text, (self.rect.centerx - 5, self.rect.centery - 7))

pygame.draw.rect(surface, GREEN if self.winner == 'X' else RED, self.rect)
for index, side in enumerate(self.sides):
if side:
pygame.draw.line(win, WHITE, self.edges[index][0], self.edges[index][1], 2)
pygame.draw.line(surface, WHITE, self.edges[index][0], self.edges[index][1], 2)

def draw_game():
win.fill(BLACK)
for r in range(ROWS + 1):
for c in range(COLS + 1):
pygame.draw.circle(win, WHITE, (c * CELL_SIZE + 2 * PADDING, r * CELL_SIZE + 3 * PADDING), 2)
for cell in cells:
cell.update(win)

def create_cells():
cells = []
for r in range(ROWS):
for c in range(COLS):
cell = Cell(r, c)
cells.append(cell)
return cells
def draw_buttons(p1_score, p2_score):
p1_button_rect = pygame.Rect(PADDING, SCREEN_HEIGHT - BUTTON_HEIGHT - BUTTON_PADDING, BUTTON_WIDTH, BUTTON_HEIGHT)
p2_button_rect = pygame.Rect(SCREEN_WIDTH - BUTTON_WIDTH - PADDING, SCREEN_HEIGHT - BUTTON_HEIGHT - BUTTON_PADDING, BUTTON_WIDTH, BUTTON_HEIGHT)

def reset_cells():
return None, None, False, False, False, False
pygame.draw.rect(win, BUTTON_COLOR, p1_button_rect)
pygame.draw.rect(win, BUTTON_COLOR, p2_button_rect)

def reset_score():
return 0, 0, 0
p1_text = font.render(f'Player 1: {p1_score}', True, BUTTON_TEXT_COLOR)
p2_text = font.render(f'Player 2: {p2_score}', True, BUTTON_TEXT_COLOR)

def reset_player():
return 0, ['X', 'O'], 'X', False
win.blit(p1_text, (p1_button_rect.centerx - p1_text.get_width() // 2, p1_button_rect.centery - p1_text.get_height() // 2))
win.blit(p2_text, (p2_button_rect.centerx - p2_text.get_width() // 2, p2_button_rect.centery - p2_text.get_height() // 2))

# Game variables initialization
# Initialize game variables
cells = []
game_over = False
cells = create_cells()
pos, current_cell, up, right, bottom, left = reset_cells()
fill_count, p1_score, p2_score = reset_score()
turn, players, current_player, next_turn = reset_player()
turn = 0
players = ['X', 'O']
player = players[turn]
next_turn = False
fill_count = 0
p1_score = 0
p2_score = 0
ccell = None
up = right = bottom = left = False

# Create the game grid
for r in range(ROWS):
for c in range(COLS):
cell = Cell(r, c)
cells.append(cell)

# Main game loop
running = True
while running:

win.fill(DARK_GRAY)

for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
pos = event.pos
elif event.type == pygame.MOUSEBUTTONUP:
pos = None
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_q or event.key == pygame.K_ESCAPE:
running = False
elif event.key == pygame.K_r:
game_over = False
cells = create_cells()
pos, current_cell, up, right, bottom, left = reset_cells()
fill_count, p1_score, p2_score = reset_score()
turn, players, current_player, next_turn = reset_player()
elif not game_over:
if event.key == pygame.K_UP:
up = True
elif event.key == pygame.K_RIGHT:
right = True
elif event.key == pygame.K_DOWN:
bottom = True
elif event.key == pygame.K_LEFT:
left = True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
up = False
elif event.key == pygame.K_RIGHT:
right = False
elif event.key == pygame.K_DOWN:
bottom = False
elif event.key == pygame.K_LEFT:
left = False

# Drawing grid
for r in range(ROWS + 1):
for c in range(COLS + 1):
pygame.draw.circle(win, WHITE, (c * CELL_SIZE + 2 * PADDING, r * CELL_SIZE + 3 * PADDING), 2)

# Update and draw cells
for cell in cells:
cell.update(win)
if pos and cell.rect.collidepoint(pos):
current_cell = cell

# Drawing current selection
if current_cell:
index = current_cell.index
if not current_cell.winner:
pygame.draw.circle(win, RED, current_cell.rect.center, 2)

if up and not current_cell.sides[0]:
current_cell.sides[0] = True
if index - ROWS >= 0:
cells[index - ROWS].sides[2] = True
next_turn = True
if right and not current_cell.sides[1]:
current_cell.sides[1] = True
if (index + 1) % COLS > 0:
cells[index + 1].sides[3] = True
next_turn = True
if bottom and not current_cell.sides[2]:
current_cell.sides[2] = True
if index + ROWS < len(cells):
cells[index + ROWS].sides[0] = True
next_turn = True
if left and not current_cell.sides[3]:
current_cell.sides[3] = True
if (index % COLS) > 0:
cells[index - 1].sides[1] = True
next_turn = True

# Check for win condition
res = current_cell.check_win(current_player)
if res:
fill_count += res
if current_player == 'X':
p1_score += 1
else:
p2_score += 1
if fill_count == ROWS * COLS:
game_over = True

# Switch players
if next_turn:
turn = (turn + 1) % len(players)
current_player = players[turn]
next_turn = False

# Display scores and current player
p1_img = font.render(f'{p1_score}', True, BLUE)
p2_img = font.render(f'{p2_score}', True, BLUE)

# Render player texts with appropriate positions
p1_text = font.render('Player 1:', True, BLUE)
p2_text = font.render('Player 2:', True, BLUE)

# Calculate positions for player texts and scores
p1_text_pos = (2 * PADDING, 15)
p1_img_pos = (p1_text_pos[0] + p1_text.get_width() + 5, 15)
p2_img_pos = (SCREEN_WIDTH - 2 * PADDING - p2_img.get_width(), 15)
p2_text_pos = (p2_img_pos[0] - p2_text.get_width() - 5, 15)

# Blit the player texts and scores
win.blit(p1_text, p1_text_pos)
win.blit(p1_img, p1_img_pos)
win.blit(p2_text, p2_text_pos)
win.blit(p2_img, p2_img_pos)

# Highlight current player's turn
if not game_over:
if turn == 0: # Player 1's turn
pygame.draw.rect(win, BLUE, (p1_text_pos[0], p1_text_pos[1] + font.get_height() + 2, p1_text.get_width() + p1_img.get_width() + 5, 2), 0)
else: # Player 2's turn
pygame.draw.rect(win, BLUE, (p2_text_pos[0], p2_text_pos[1] + font.get_height() + 2, p2_text.get_width() + p2_img.get_width() + 5, 2), 0)

if game_over:
# Display game over message
overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
overlay.set_alpha(200)
overlay.fill(BLACK)
win.blit(overlay, (0, 0))
over_img = font.render('Game Over', True,WHITE )
winner_img = font.render(f'Player {1 if p1_score > p2_score else 2} Won', True, GREEN)
msg_img = font.render('Press R to restart, Q or ESC to quit', True, RED)
win.blit(over_img, ((SCREEN_WIDTH - over_img.get_width()) / 2, 100))
win.blit(winner_img, ((SCREEN_WIDTH - winner_img.get_width()) / 2, 150))
win.blit(msg_img, ((SCREEN_WIDTH - msg_img.get_width()) / 2, 200))

# Draw border
pygame.draw.rect(win, LIGHT_GRAY, (0, 0, SCREEN_WIDTH, SCREEN_HEIGHT), 2, border_radius=10)

def draw_button(text, color, x, y, action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()

if x + button_width > mouse[0] > x and y + button_height > mouse[1] > y:
pygame.draw.rect(screen, color, (x, y, button_width, button_height))
if click[0] == 1 and action:
action()
else:
pygame.draw.rect(screen, color, (x, y, button_width, button_height))

text_surf = font.render(text, True, WHITE)
text_rect = text_surf.get_rect(center=(x + button_width / 2, y + button_height / 2))
screen.blit(text_surf, text_rect)

def replay_game():
main()

def quit_game():
pygame.quit()
sys.exit()

def main():
clock = pygame.time.Clock()
running = True

while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()

screen.fill(WHITE)

# Game logic and drawing go here

# Draw buttons
draw_button("Replay", BLUE, SCREEN_WIDTH // 4 - button_width // 2, SCREEN_HEIGHT // 2, replay_game)
draw_button("Quit", RED, 3 * SCREEN_WIDTH // 4 - button_width // 2, SCREEN_HEIGHT // 2, quit_game)


elif event.type == pygame.MOUSEBUTTONDOWN and not game_over:
x, y = event.pos
for cell in cells:
if cell.rect.collidepoint(x, y):
for i, edge in enumerate(cell.edges):
if not cell.sides[i] and pygame.Rect(edge[0], (edge[1][0] - edge[0][0], edge[1][1] - edge[0][1])).inflate(5, 5).collidepoint(x, y):
cell.sides[i] = True
if cell.check_win(player):
if player == 'X':
p1_score += 1
else:
p2_score += 1
else:
turn = (turn + 1) % 2
player = players[turn]
break

draw_game()
draw_buttons(p1_score, p2_score)
pygame.display.update()

pygame.quit()

pygame.display.flip()
clock.tick(60)

if __name__ == "__main__":
main()