Skip to content
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
57 changes: 57 additions & 0 deletions Games/Turtle race/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Turtle Race</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: #f4f4f4;
margin-top: 20px;
}
canvas {
border: 2px solid #333;
background-color: #fafafa;
}
#controls {
margin-top: 20px;
display: flex;
gap: 10px;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
background-color: #007bff;
color: white;
border: none;
border-radius: 5px;
}
button:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
#result {
margin-top: 15px;
font-size: 1.2em;
font-weight: bold;
color: #333;
}
</style>
</head>
<body>
<h1>Turtle Race Championship</h1>
<canvas id="raceCanvas" width="500" height="400"></canvas>
<div id="controls">
<button id="startButton">Start Race</button>
</div>
<p id="result">Place your bet by clicking "Start Race".</p>

<script src="race.js"></script>
</body>
</html>
38 changes: 38 additions & 0 deletions Games/Turtle race/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Created this file for better experience and for running locally with actual turtle shapes

import turtle as t
from turtle import Screen
import random

is_race_on = False
screen = Screen()
screen.setup(500,400)
user_bet = screen.textinput(title="Turtle race", prompt="Place your bets, Which turtle would win the race: ?")
colors = ["red","blue","green","yellow","cyan"]
positions = [-70,-40,-10,20,50]
all_turtles = []

for turtle_index in range(0,5):
new_turtle = t.Turtle()
new_turtle.shape("turtle")
new_turtle.color(colors[turtle_index])
new_turtle.penup()
new_turtle.goto(x = -230, y = positions[turtle_index])
all_turtles.append(new_turtle)

if user_bet:
is_race_on = True

while is_race_on:
for turtle in all_turtles:
if turtle.xcor() > 230:
is_race_on = False
winning_color = turtle.pencolor()
if winning_color == user_bet:
print(f"You've won!, winning color was {winning_color}")
else:
print(f"You've lost!, winning color was {winning_color}")
random_distance = random.randint(0, 10)
turtle.forward(random_distance)

screen.exitonclick()
212 changes: 212 additions & 0 deletions Games/Turtle race/race.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
// --- Setup ---
const canvas = document.getElementById('raceCanvas');
const ctx = canvas.getContext('2d');
const startButton = document.getElementById('startButton');
const resultDisplay = document.getElementById('result');

const colors = ["red", "blue", "green", "yellow", "cyan"];
const startPositionsY = [70, 120, 170, 220, 270]; // Adjusted Y positions for canvas coordinates
const startX = 20;
const finishLineX = canvas.width - 40;
const turtleSize = 20; // Size of the turtle (will be the diameter/width)

let turtles = [];
let userBet = "";
let raceInProgress = false;

// --- Turtle Class / Object Creation ---

/**
* Creates the initial set of turtle objects.
*/
function setupTurtles() {
turtles = []; // Reset turtles array for a new race
for (let i = 0; i < colors.length; i++) {
turtles.push({
id: i,
color: colors[i],
x: startX,
y: startPositionsY[i]
});
}
}

// --- Drawing Functions ---

/**
* Draws a simple turtle shape on the canvas.
* @param {CanvasRenderingContext2D} context - The canvas rendering context.
* @param {number} x - The x-coordinate of the turtle's center.
* @param {number} y - The y-coordinate of the turtle's center.
* @param {number} size - The overall size of the turtle.
* @param {string} color - The fill color of the turtle.
*/
function drawTurtleShape(context, x, y, size, color) {
context.fillStyle = color;
context.strokeStyle = 'black';
context.lineWidth = 1;

context.beginPath();

// Body (simple oval/rounded rectangle)
const bodyWidth = size * 1.5;
const bodyHeight = size * 0.8;
const halfBodyWidth = bodyWidth / 2;
const halfBodyHeight = bodyHeight / 2;

context.moveTo(x - halfBodyWidth + halfBodyHeight, y - halfBodyHeight);
context.arcTo(x + halfBodyWidth, y - halfBodyHeight, x + halfBodyWidth, y + halfBodyHeight, halfBodyHeight);
context.arcTo(x + halfBodyWidth, y + halfBodyHeight, x - halfBodyWidth, y + halfBodyHeight, halfBodyHeight);
context.arcTo(x - halfBodyWidth, y + halfBodyHeight, x - halfBodyWidth, y - halfBodyHeight, halfBodyHeight);
context.arcTo(x - halfBodyWidth, y - halfBodyHeight, x + halfBodyWidth, y - halfBodyHeight, halfBodyHeight);
context.closePath();
context.fill();
context.stroke();

// Head
const headRadius = size * 0.3;
context.beginPath();
context.arc(x + halfBodyWidth + headRadius * 0.8, y, headRadius, 0, Math.PI * 2);
context.fill();
context.stroke();

// Tail
context.beginPath();
context.moveTo(x - halfBodyWidth, y);
context.lineTo(x - halfBodyWidth - size * 0.3, y - size * 0.15);
context.lineTo(x - halfBodyWidth - size * 0.3, y + size * 0.15);
context.closePath();
context.fill();
context.stroke();

// Legs (simple rectangles)
const legWidth = size * 0.2;
const legHeight = size * 0.3;
// Front-top leg
context.fillRect(x + halfBodyWidth * 0.4, y - halfBodyHeight - legHeight * 0.5, legWidth, legHeight);
context.strokeRect(x + halfBodyWidth * 0.4, y - halfBodyHeight - legHeight * 0.5, legWidth, legHeight);
// Back-top leg
context.fillRect(x - halfBodyWidth * 0.8, y - halfBodyHeight - legHeight * 0.5, legWidth, legHeight);
context.strokeRect(x - halfBodyWidth * 0.8, y - halfBodyHeight - legHeight * 0.5, legWidth, legHeight);
// Front-bottom leg
context.fillRect(x + halfBodyWidth * 0.4, y + halfBodyHeight - legHeight * 0.5, legWidth, legHeight);
context.strokeRect(x + halfBodyWidth * 0.4, y + halfBodyHeight - legHeight * 0.5, legWidth, legHeight);
// Back-bottom leg
context.fillRect(x - halfBodyWidth * 0.8, y + halfBodyHeight - legHeight * 0.5, legWidth, legHeight);
context.strokeRect(x - halfBodyWidth * 0.8, y + halfBodyHeight - legHeight * 0.5, legWidth, legHeight);
}

/**
* Draws a single turtle on the canvas.
* @param {object} turtle - The turtle object to draw.
*/
function drawTurtle(turtle) {
// Call the new drawing function
// We adjust y by -turtleSize/2 so the turtle's body is centered on its track line
drawTurtleShape(ctx, turtle.x + turtleSize / 2, turtle.y, turtleSize, turtle.color);
}

/**
* Draws the finish line on the canvas.
*/
function drawFinishLine() {
ctx.strokeStyle = "black";
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(finishLineX, 0);
ctx.lineTo(finishLineX, canvas.height);
ctx.stroke();
}

/**
* Clears and redraws the entire scene (turtles and finish line).
*/
function drawScene() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawFinishLine();
turtles.forEach(drawTurtle);
}

// --- Game Logic ---

/**
* The main animation loop for the race.
*/
function raceLoop() {
if (!raceInProgress) return;

let winner = null;

// Move each turtle by a random amount
for (const turtle of turtles) {
// Reduced speed here for demonstration. Change '11' for desired speed.
const randomDistance = Math.floor(Math.random() * 3); // random integer between 0 and 4 (slower)
turtle.x += randomDistance;

// Check for win condition
if (turtle.x >= finishLineX) {
winner = turtle;
raceInProgress = false;
break; // Stop loop once a winner crosses the line
}
}

drawScene(); // Redraw turtles in new positions

// Continue animation or declare winner
if (raceInProgress) {
requestAnimationFrame(raceLoop);
} else if (winner) {
announceWinner(winner);
}
}

/**
* Displays the result of the race and compares it to the user's bet.
* @param {object} winningTurtle - The turtle object that won.
*/
function announceWinner(winningTurtle) {
const winningColor = winningTurtle.color;
let resultMessage = `The winner is the ${winningColor} turtle! `;

if (winningColor === userBet) {
resultMessage += "You won the bet!";
} else {
resultMessage += "You lost the bet.";
}
resultDisplay.textContent = resultMessage;
startButton.disabled = false; // Enable button for a new race
startButton.textContent = "Restart Race";
}

// --- Initialization and Event Listeners ---

/**
* Starts the entire race process.
*/
function startRace() {
// 1. Get user input
const betPrompt = `Place your bets. Which turtle will win? (${colors.join(", ")})`;
userBet = prompt(betPrompt)?.toLowerCase();

if (!userBet || !colors.includes(userBet)) {
alert("Invalid bet. Please enter one of the listed colors.");
return;
}

// 2. Setup game state
raceInProgress = true;
startButton.disabled = true;
resultDisplay.textContent = `Your bet is on: ${userBet}. Race started!`;
setupTurtles();

// 3. Start animation loop
requestAnimationFrame(raceLoop);
}

// Initial setup on page load
setupTurtles();
drawScene();

// Bind start button click event
startButton.addEventListener('click', startRace);