0% found this document useful (0 votes)
45 views18 pages

Recess-CS project

The 'Recess Game' is an interactive application that allows users to play football and Tic-Tac-Toe, designed to evoke childhood nostalgia. Built with Python using Tkinter and Pygame, it features a user-friendly interface and a countdown timer to simulate a recess break. The project serves as a practical learning opportunity in game development, AI interaction, and interface design.

Uploaded by

aimee97330361
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views18 pages

Recess-CS project

The 'Recess Game' is an interactive application that allows users to play football and Tic-Tac-Toe, designed to evoke childhood nostalgia. Built with Python using Tkinter and Pygame, it features a user-friendly interface and a countdown timer to simulate a recess break. The project serves as a practical learning opportunity in game development, AI interaction, and interface design.

Uploaded by

aimee97330361
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

COMPUTER SCIENCE

PROJECT REPORT

RECESS

Submitted by:
Aimee Vinod, Alwin PA, Amal Jose, Hari Govind
Index
Sl. no Pg no
1. Synopsis
2. Introduction
3. Project configuration
3.1 Hardware requirements
3.2 Software requirements
4. Software description
5. Source code
6. Conclusion
7. Bibliography
1. Synopsis
The “Recess Game” is an interactive application designed to bring the joy and excitement of
childhood play onto our screens. Inspired by our playful spirits as children, the game
features two popular games—football (soccer) and Tic-Tac-Toe—giving users a chance to
relive the carefree moments of their early school days, where a simple recess break could
turn into hours of fun. Built using Python and leveraging the Tkinter and Pygame libraries,
the application offers a clean and intuitive interface, allowing users to easily navigate
between the two games.

The football game allows players to challenge a simple AI opponent, simulating a


mini-soccer match, while Tic-Tac-Toe offers a quick strategic battle of wits. To enhance the
playful atmosphere, the app also features a countdown timer that simulates a recess break,
with a bell to mark the end of the period. The game aims to provide an easy-to-use and
nostalgic experience, offering both entertainment and a brief mental escape, reminiscent of
the lighthearted moments we cherished as children.

By incorporating user interface design, game mechanics, AI for the football game, and sound
integration, this project showcases fundamental aspects of game development, while
keeping the focus on simplicity and fun.
2. Introduction

From KG to high school, recess was the period we eagerly awaited. It wasn’t just a break
from the monotony of lessons, but a chance to break free and play with our friends. Whether
we were running around playing football or challenging each other in games of Tic-Tac-Toe
during a particularly boring class, these moments were an essential part of our childhood.
The desire to relive those carefree times—filled with friendly competition, laughter, and
spontaneous play—served as the inspiration behind our project.

The "Recess Game” brings that sense of joy and nostalgia to life by offering an interactive
platform where users can play two beloved games—football and Tic-Tac-Toe. Built using
Python and the Tkinter and Pygame libraries, the game is designed to be simple, engaging,
and accessible for players of all ages. Our goal was to capture the essence of school recess,
where fun and friendly competition could happen at the touch of a button.

Through this project, we wanted to explore the integration of interactive games with
graphical interfaces and sound effects. By simulating a “recess” period with a countdown
timer, we’ve created an experience that mimics the fun we had during our school days. This
project not only helps us revisit those cherished memories but also provides a practical
learning opportunity in game development, AI interaction, and interface design
3. Project Configuration

Hardware Requirements

1. Processor: Minimum 1.6 GHz dual-core processor (Recommended: 2.4 GHz


quad-core or higher)
2. RAM: At least 4 GB
3. Storage: Minimum 500 MB of free space for installation and dependencies
4. Display: A monitor with a minimum resolution of 1024 x 768
5. Input Devices: Keyboard and mouse (or touchpad)
6. Sound Card: Required for audio effects in the game

Software Requirements

1. Operating System:

Windows 10 or higher

2. Python Version:

Python 3.8 or higher

3. Required Python Libraries:

Pygame for implementing the football game and handling graphics/audio

Tkinter (built-in with Python) for creating the GUI and handling the Tic-Tac-Toe game

Time (standard library) for countdown timer functionality

Os (standard library) for managing sound files

4. IDE/Text Editor (any of the following)


Python3
IDLE

Other tools

1.Assets:
Audio files for sound effects
2.Dependencies Installation:
Use pip to install necessary libraries (e.g., pip install pygame)
4. Software description

•Python
Python is the primary programming language used in this project. It provides the necessary
structure and functionality to implement the game logic, handle user input, and manage
program flow. Python’s simplicity and readability make it an ideal choice for this project.

•Pygame
Pygame is used for handling the game’s graphics and sound. It allows the creation of
interactive 2D elements, such as the game’s interface, animations, and sound effects,
enhancing the overall user experience.

•Tkinter
Tkinter is a built-in Python library used for creating graphical user interfaces (GUIs). It is
utilized in this project to manage the game’s window, display text, and handle button
interactions for starting the game.

•Math
The math module is used for performing mathematical operations in the game. It helps with
random number generation, calculations related to game mechanics, and any mathematical
logic needed during gameplay.

•Subprocess
Subprocess is used to run external commands or scripts from within the Python program. It
helps in managing background processes or interacting with system-level tasks, such as
executing scripts or launching applications if required by the project.

•Random
The random module is used to generate random events in the game, such as determining
the outcome of certain actions. It adds unpredictability to the gameplay, making the
experience more dynamic and engaging
5. SOURCE CODE

#RECESS MAIN CODE


Import tkinter as tk
From tkinter import messagebox
Import subprocess
Import pygame

# Function to start a game using Popen


Def run_game(script_name):
Try:
Subprocess.Popen([‘python3’, script_name]) # Non-blocking process Except
FileNotFoundError:
Messagebox.showerror(“Error”, f”Cannot find the file: {script_name}”)
Main_menu() # Return to the main menu immediately

# Function to start football game


Def start_football():
Run_game(‘futbol.py’)

# Function to start Tic Tac Toe game


Def start_ttt():
Run_game(‘ttt.py’)

# Function to display main menu Def main_menu():


For widget in root.winfo_children():
Widget.destroy()

# Background image
Bg_label = tk.Label(root, image=bg_image)
Bg_label.place(x=0, y=0, relwidth=1, relheight=1)

# Dialogue
Dialogue = tk.Label(
Root,
Text=”Do you want to play Football or Tic Tac Toe?”,
Font=(“Courier”, 16), # Use Courier for a playful font
Bg=”#ffffff”,
Wraplength=500
)
Dialogue.place(relx=0.5, rely=0.1, anchor=”n”)

# Buttons
Football_button = tk.Button(
Root, text=”Football”, font=(“Courier”, 14), command=start_football
)
Football_button.place(relx=0.3, rely=0.3)
Ttt_button = tk.Button(
Root, text=”Tic Tac Toe”, font=(“Courier”, 14), command=start_ttt
)
Ttt_button.place(relx=0.6, rely=0.3)

# End of recess function Def end_recess():


Pygame.mixer.init()
Pygame.mixer.music.load(“bellsound.mp3”) Pygame.mixer.music.play()

# Show message that recess is over


Root.after(3000, lambda: root.quit()) # Wait for 3 seconds and quit
Root.after(3000, lambda: messagebox.showinfo(“Time’s Up”, “Recess is over!”))

# Main application window


Root = tk.Tk()
Root.title(“Recess Game”)
Root.geometry(“800x600”)

# Load the image for the background


Try:
Bg_image = tk.PhotoImage(file=”school_field.png”)
Except Exception as e:
Print(f”Error loading image: {e}”)

Main_menu()

# End recess after 2 minutes (120,000 ms)


Root.after(120000, end_recess) # 2 minutes = 120,000 ms

Root.mainloop()

#FOOTBALL CODE import pygame import math import random import sys

# Initialize Pygame pygame.init()

# Display settings
WIDTH, HEIGHT = 800, 500 screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Mini Soccer Game")

# Colors
GREEN = (34, 139, 34)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
# Game settings
FPS = 60
PLAYER_SPEED = 5
AI_SPEED = 3
BALL_SPEED = 5
GOAL_WIDTH = 100
GOAL_HEIGHT = 150

# Initialize clock clock = pygame.time.Clock()

# Player, AI, and Ball settings player_size = 30 ai_size = 30 ball_radius = 20

# Positions and directions player_pos = [WIDTH - 70, HEIGHT //


2] ai_pos = [70, HEIGHT // 2] ball_pos = [WIDTH // 2, HEIGHT //
2] ball_direction = [random.choice([-1, 1]), random.choice([-1,
1])]

# Score tracking player_score = 0 ai_score


=0

# Game timer start_time = pygame.time.get_ticks() # Get the starting time game_duration =


30000 # 30 seconds

# Function to draw the field def draw_field(): screen.fill(GREEN) # Center line


pygame.draw.line(screen, WHITE, (WIDTH // 2, 0), (WIDTH // 2,
HEIGHT), 5)
# Center circle pygame.draw.circle(screen, WHITE, (WIDTH // 2,
HEIGHT // 2), 50, 5)
# Goals
pygame.draw.rect(screen, WHITE, (WIDTH - 10, HEIGHT // 2 - GOAL_HEIGHT // 2, 10,
GOAL_HEIGHT)) pygame.draw.rect(screen, WHITE, (0, HEIGHT // 2 - GOAL_HEIGHT //
2, 10, GOAL_HEIGHT))

# Function to draw a triangle def draw_triangle(position, color, size, facing_right): points


=[
(position[0], position[1] - size),
(position[0] - size if facing_right else position[0] + size, position[1] + size),
(position[0] + size if facing_right else position[0] - size, position[1] + size)
]
pygame.draw.polygon(screen, color, points)

# Function to draw a hexagon for the ball def draw_hexagon(position, color, radius):
points = [
(position[0] + radius * math.cos(math.radians(angle)), position[1] + radius *
math.sin(math.radians(angle))) for angle in range(0, 360, 60)
]
pygame.draw.polygon(screen, color, points)
# Function to move the ball def move_ball():
global ball_pos, ball_direction, player_score, ai_score

# Move the ball ball_pos[0] += BALL_SPEED


* ball_direction[0] ball_pos[1] += BALL_SPEED
* ball_direction[1]

# Ball collision with top and bottom walls if ball_pos[1] <= ball_radius or ball_pos[1] >=
HEIGHT - ball_radius:
ball_direction[1] = -ball_direction[1]

# Ball collision with goals if ball_pos[0] <= ball_radius: # Check if it enters the goal
if HEIGHT // 2 - GOAL_HEIGHT // 2 < ball_pos[1] < HEIGHT // 2 + GOAL_HEIGHT
// 2: player_score += 1 reset_ball() elif ball_pos[0] >= WIDTH - ball_radius:
# Check if it enters the goal if HEIGHT // 2 - GOAL_HEIGHT // 2 <
ball_pos[1] < HEIGHT // 2 + GOAL_HEIGHT // 2:
ai_score += 1 reset_ball()

# Function to reset the ball to the center def reset_ball():


global ball_pos, ball_direction ball_pos = [WIDTH // 2, HEIGHT // 2] ball_direction =
[random.choice([-1, 1]), random.choice([-1, 1])]

# Function to handle player input def move_player(keys): if keys[pygame.K_UP] and


player_pos[1] > player_size:
player_pos[1] -= PLAYER_SPEED if keys[pygame.K_DOWN] and player_pos[1] <
HEIGHT - player_size:
player_pos[1] += PLAYER_SPEED if keys[pygame.K_LEFT] and player_pos[0] >
WIDTH // 2 + player_size:
player_pos[0] -= PLAYER_SPEED if keys[pygame.K_RIGHT] and player_pos[0] <
WIDTH - player_size: player_pos[0] +=
PLAYER_SPEED

# Function to move the AI def move_ai():


# Simple AI that moves toward the ball's y-position if ball_pos[1] < ai_pos[1] and
ai_pos[1] > ai_size: ai_pos[1]
-= AI_SPEED elif ball_pos[1] > ai_pos[1] and ai_pos[1] <
HEIGHT - ai_size: ai_pos[1] += AI_SPEED

# Function to check collision between player/AI and ball def check_collision(): global
ball_direction

# Check collision with player if math.hypot(player_pos[0] - ball_pos[0], player_pos[1]


- ball_pos[1]) <= player_size + ball_radius: ball_direction[0] = -ball_direction[0]

# Check collision with AI if math.hypot(ai_pos[0] - ball_pos[0], ai_pos[1] - ball_pos[1])


<= ai_size + ball_radius:
ball_direction[0] = -ball_direction[0]
# Function to display the timer def display_timer():
elapsed_time = pygame.time.get_ticks() - start_time remaining_time = max(0,
(game_duration - elapsed_time) // 1000) # Time in seconds font =
pygame.font.Font(None,
36) timer_text = font.render(f"Time: {remaining_time}s",
True, WHITE) screen.blit(timer_text, (WIDTH // 2 - 70, 20)) return remaining_time

# Game loop running = True while running: for event in pygame.event.get(): if


event.type
== pygame.QUIT:
running = False

# Get keys pressed keys =


pygame.key.get_pressed()

# Draw everything draw_field() draw_triangle(player_pos,


BLUE, player_size, True) # Player triangle draw_triangle(ai_pos,
RED, ai_size, False) # AI triangle draw_hexagon(ball_pos,
YELLOW, ball_radius) # Ball hexagon

# Move and check collisions move_player(keys) move_ai() move_ball()


check_collision()

# Display scores font = pygame.font.Font(None, 36) player_text =


font.render(f"Player: {player_score}", True, BLUE) ai_text = font.render(f"AI: {ai_score}",
True, RED) screen.blit(player_text, (WIDTH - 150, 20)) screen.blit(ai_text,
(20, 20))

# Display timer remaining_time = display_timer()

# End game if timer is up if remaining_time == 0:


running = False winner = "Player" if player_score > ai_score else
"AI" font = pygame.font.Font(None, 48) end_text = font.render(f"Game Over!
{winner} wins!", True, WHITE) screen.blit(end_text, (WIDTH // 2 - 150, HEIGHT // 2))
pygame.display.flip() pygame.time.wait(3000) # Wait for 3 seconds before closing the game

# Update display pygame.display.flip() clock.tick(FPS)

pygame.quit()
sys.exit()

#TIC-TAC-TOE

import tkinter as tk import random

# Define the main game class


class TicTacToe: def
__init__(self, root):
self.root = root self.root.title("Tic-Tac-
Toe")

# Customize theme colors self.bg_color


= "#F2D7D5" # Light pink self.button_color
= "#E59866" # Soft orange self.text_color =
"#6E2C00" # Dark brown self.grid_color =
"#D7BDE2" # Light purple self.font_style =
"Arial 20 bold"

# Set background color for the window self.root.configure(bg=self.bg_color)

# Initialize the board self.board = [' ' for _ in range(9)] # 3x3 board
self.current_player
= 'X' self.game_over = False

# Score tracking self.rounds_played = 0 self.x_wins


=0 self.o_wins
=0

# Create the GUI buttons self.buttons = [] for i in range(9): button =


tk.Button(
root, text=" ", font=self.font_style,
bg=self.button_color, fg=self.text_color, width=8, height=3,
relief="ridge",
command=lambda i=i: self.button_click(i)
)
self.buttons.append(button)

# Arrange buttons in a grid for i, button in enumerate(self.buttons):


row, col = divmod(i, 3)
button.grid(row=row, column=col, padx=5, pady=5)

# Create a reset button self.reset_button


= tk.Button(
root, text="Reset", font="Arial 14 bold", bg=self.grid_color,
fg=self.text_color, width=20, height=2,
command=self.reset_game
)
self.reset_button.grid(row=3, column=0, columnspan=3, pady=(10, 0))

# Status label for displaying player turns and results self.status_label = tk.Label(
root, text="Player X's turn", font="Arial 14 bold", bg=self.bg_color,
fg=self.text_color
)
self.status_label.grid(row=4, column=0, columnspan=3, pady=(5, 0))
# Score label to track wins self.score_label = tk.Label(
root, text="Score:
X: 0 | O: 0", font="Arial
14 bold",
bg=self.bg_color, fg=self.text_color
)
self.score_label.grid(row=5, column=0, columnspan=3)

def button_click(self, index): # Handle button click events if self.board[index] == '


' and not self.game_over:
self.board[index] = self.current_player
self.buttons[index].config(text=self.current_player)

if self.check_winner(self.current_player):
self.end_round(winner=self.current_player)
return elif ' '
not in self.board:
self.end_round(winner=None)
return
# Switch players self.current_player = 'O' if self.current_player
== 'X' else 'X' self.status_label.config(text=f"Player
{self.current_player}'s turn")

if self.current_player == 'O' and not self.game_over:


self.ai_move()

def ai_move(self): # AI makes a move move = self.get_best_move()


self.board[move] = 'O' self.buttons[move].config(text='O')

if self.check_winner('O'): self.end_round(winner='O') elif ' ' not in self.board:


self.end_round(winner=None)
else:
self.current_player = 'X' self.status_label.config(text="Player X's turn")

def get_best_move(self):
# 70% chance to make an optimal move, 30% chance to make a random move if
random.random() < 0.7:
# Try to win, block, or take a strategic move for i in range(9): if
self.board[i] == ' ':
self.board[i] = 'O' if self.check_winner('O'):
self.board[i] = ' ' # Undo move return i
self.board[i] = ' ' # Undo
move
# Block the player from winning
for i in range(9): if self.board[i]
== ' ': self.board[i] = 'X' if
self.check_winner('X'):
self.board[i] = ' ' # Undo move return i
self.board[i] = ' ' # Undo
move

# Otherwise, pick a strategic position (center or corners) strategic_moves =


[4, 0, 2, 6, 8] # Prefer center and corners for move in strategic_moves: if
self.board[move] == ' ':
return move

# If no strategic moves are available, pick a random spot return


random.choice([i for i, spot in enumerate(self.board) if spot == ' '])
else:
# 30% chance to make a random move return random.choice([i for i, spot in
enumerate(self.board) if spot == ' '])

def check_winner(self, player): # Check all winning patterns win_patterns = [(0,


1,
2), (3, 4, 5), (6, 7, 8),
(0, 3, 6), (1, 4, 7), (2, 5, 8),
(0, 4, 8), (2, 4, 6)]

for pattern in win_patterns: if self.board[pattern[0]] == self.board[pattern[1]] ==


self.board[pattern[2]] == player:
return True
return False def end_round(self, winner): # Handle the end of a round
self.game_over = True if winner == 'X': self.x_wins += 1
self.status_label.config(text="Player X wins this round!") elif winner == 'O':
self.o_wins += 1 self.status_label.config(text="Player O wins this round!")
else:
self.status_label.config(text="It's a draw this round!")

self.rounds_played += 1 self.update_score()

if self.rounds_played >= 5:
self.declare_winner()
else:
self.root.after(2000, self.reset_game) # Delay reset for 2 seconds

def reset_game(self):
# Reset the board for a new round self.board = [' ' for _ in range(9)] for button
in self.buttons:
button.config(text=" ", bg=self.button_color) self.current_player = 'X'
self.game_over = False
if self.rounds_played < 5:
self.status_label.config(text="Player X's turn")

def update_score(self): # Update the score display


self.score_label.config(text=f"Score: X: {self.x_wins} | O: {self.o_wins}")
def declare_winner(self):
# Declare the final winner after 5 rounds if self.x_wins > self.o_wins:
self.status_label.config(text="Player X wins the best of 5!") elif self.o_wins >
self.x_wins:
self.status_label.config(text="Player O wins the best of 5!")
else:
self.status_label.config(text="It's a tie in the best of 5!")
self.reset_button.config(state=tk.DISABLED) # Disable further resets # Set up the main
application window def main():
root = tk.Tk() game =
TicTacToe(root) root.mainloop()

if __name__ == "__main__":
main()

Output
6. Conclusion

In conclusion, this project has provided valuable insights into the process of game
development using Python. By utilizing libraries such as Tkinter for the graphical interface
and Pygame for interactive elements, we successfully created two engaging games: Tic Tac
Toe and Football. These games were designed to be simple yet enjoyable, focusing on user
interaction and providing a satisfying experience.

Throughout the development process, we gained a deeper understanding of handling


events, user input, and creating responsive game environments. The project allowed us to
apply theoretical knowledge in a practical setting, enhancing our programming skills and
problem-solving abilities. It also highlighted the importance of user-friendly design and
efficient coding practices in game development. While the games are relatively simple, the
project serves as a foundation for more advanced work in the future. We are now better
equipped to explore more complex programming concepts and improve our game
development techniques.

Overall, this project has been an excellent learning experience, helping us build both
technical and creative skills that will benefit us in future endeavors.
7. Bibliography

1.Web Resources:

Pygame Documentation. Retrieved from https://www.pygame.org/docs/

Python Official Documentation. Retrieved from https://docs.python.org/3/

TutorialsPoint. “Python Tkinter Tutorial.” Retrieved from


https://www.tutorialspoint.com/python/python_gui_programming.htm

2.Project Assistance:

OpenAI’s ChatGPT for conceptualizing and refining the project.

3.Audio and Graphic Assets:

FreeSound.org. “Bell Sound Effects.” Retrieved from https://freesound.org/


Not copyrighted
OpenGameArt.org. “Game Graphics.” Retrieved from https://opengameart.org/

4.Tools and Software:

Python Software Foundation. Python Version 3. Retrieved from https://www.python.org/

Visual Studio Code. Microsoft Corporation. Retrieved from https://code.visualstudio.com/

Sure! Here’s a concise YouTube-only bibliography for you:

5.YouTube Tutorials
Tech With Tim. “How to Install Python and Pygame on Windows.” YouTube, 2020.
Python Engineer. “How to Make a Game in Python using Pygame – Full Tutorial.” YouTube,
2021.
FreeCodeCamp.org. “How to Make Your First Game with Python and Pygame.” YouTube,
2021.

You might also like