So, you want to make a game? Python and JavaScript are a great combo for getting started, especially if you're a beginner. Python is fantastic for handling the game's logic and backend, while JavaScript is perfect for the frontend—what players actually see and interact with. Let's walk through how you can create a simple text-based guessing game.
Part 1: Setting Up with Python
We'll start with Python. The game's core logic will be a simple "guess the number" game. The computer will pick a random number, and the player will try to guess it.
Here's the Python code for our game's backend. You can save this as
game_logic.py.
import random
def generate_random_number():
"""Generates a random number between 1 and 100."""
return random.randint(1, 100)
def check_guess(guess, number_to_guess):
"""Checks if the player's guess is too high, too low, or correct."""
try:
guess = int(guess)
if guess < number_to_guess:
return "low"
elif guess > number_to_guess:
return "high"
else:
return "correct"
except ValueError:
return "invalid"
This code has two simple functions: generate_random_number to create the number to be guessed and check_guess to compare the player's input with the number. The check_guess function returns a string that tells us the outcome.
To use this with JavaScript, you'd typically need a way for them to communicate. A simple approach is to use a web framework like Flask in Python to create a small API.
Here's a basic Flask setup:
from flask import Flask, request, jsonify
from game_logic import generate_random_number, check_guess
from flask_cors import CORS # Important for allowing requests from your HTML file
app = Flask(__name__)
CORS(app)
number_to_guess = generate_random_number()
@app.route('/guess', methods=['POST'])
def make_guess():
global number_to_guess # Use global to modify the variable
data = request.json
guess = data.get('guess')
if guess is None:
return jsonify({"result": "invalid"})
result = check_guess(guess, number_to_guess)
if result == "correct":
# If the guess is correct, reset the number for a new game
number_to_guess = generate_random_number()
return jsonify({"result": "correct"})
else:
return jsonify({"result": result})
if __name__ == '__main__':
app.run(debug=True)
This Flask app listens for a POST request at the /guess endpoint. It takes the player's guess from the request, uses our Python logic to check it, and sends back a JSON response. The CORS library is crucial for allowing your HTML page (running locally) to send requests to your Python server.
Part 2: Building the Frontend with JavaScript & HTML
Now for the fun part: making a user interface. This is where JavaScript and HTML shine. We'll create a simple webpage with an input field and a button.
Save the following code as
index.html.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Guess the Number!</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
#game-container {
border: 1px solid #ccc;
padding: 20px;
width: 300px;
margin: auto;
border-radius: 8px;
}
</style>
</head>
<body>
<div id="game-container">
<h1>Guess the Number!</h1>
<p>I've picked a number between 1 and 100. Can you guess it?</p>
<input type="text" id="user-guess" placeholder="Enter your guess">
<button id="submit-button">Guess</button>
<p id="feedback"></p>
</div>
<script>
const submitButton = document.getElementById('submit-button');
const userGuessInput = document.getElementById('user-guess');
const feedbackParagraph = document.getElementById('feedback');
submitButton.addEventListener('click', async () => {
const guess = userGuessInput.value;
if (guess === "") {
feedbackParagraph.textContent = "Please enter a number.";
return;
}
try {
const response = await fetch('http://127.0.0.1:5000/guess', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ guess: guess }),
});
const data = await response.json();
const result = data.result;
if (result === 'low') {
feedbackParagraph.textContent = "Too low! Try again.";
} else if (result === 'high') {
feedbackParagraph.textContent = "Too high! Try again.";
} else if (result === 'correct') {
feedbackParagraph.textContent = "You got it! 🎉 A new number has been chosen.";
userGuessInput.value = ""; // Clear the input
} else {
feedbackParagraph.textContent = "Invalid input. Please enter a number.";
}
} catch (error) {
feedbackParagraph.textContent = "Could not connect to the game server.";
console.error('Error:', error);
}
});
</script>
</body>
</html>
The JavaScript in this file is the "brain" of our frontend. It waits for the user to click the "Guess" button, then sends their input to our Python server using the Fetch API. It then takes the response from the server and updates the feedback message on the page.
How to Run Your Game
Install Python: Make sure you have Python installed.
Install Flask: Open your terminal and run pip install Flask Flask-Cors.
Run the Python Server: Save the Python code as app.py (or whatever you like) and run python app.py in your terminal. You should see a message saying the server is running.
Open the HTML File: Double-click the index.html file in your browser.
Play! Type a number in the box and click the "Guess" button. The Python backend will tell the JavaScript frontend whether you were too high, too low, or just right!
And there you have it—a simple but functional game that uses both Python and JavaScript. This approach, using a backend language for logic and a frontend language for the interface, is the foundation for countless web applications and games.
Top comments (0)