Create a Chess Game in Python Step-by-Step (Source Code)

Faraz

By Faraz - July 21, 2024

Learn how to create a fully functional chess game in Python using the Pygame library. Follow this step-by-step tutorial for game development enthusiasts.

Create Chess Game in Python Step-by-Step.png

Are you ready to embark on a journey into the captivating world of chess programming? Look no further! In this Pygame tutorial, we will dive headfirst into the realm of Python-powered chess games, helping you create a masterpiece that will leave enthusiasts in awe.

Table of Contents

  • Introduction

Getting Started with Python Chess Game Tutorial with Pygame

  • Python Chess Game Tutorial with Pygame
  • Full Source Code
  • Explanation of Source Code

1. Introduction

Welcome to the Python Chess Game Tutorial with Pygame! Chess is a timeless game that has captured the hearts and minds of players for centuries. If you've ever wondered how to develop your own chess game and bring it to life, you're in the right place. In this comprehensive tutorial, we will guide you through the entire process, from setting up your development environment to building a fully functional chess game using Python and Pygame.

So, let's embark on this exciting journey and explore the world of chess game development. Whether you're a beginner looking to learn Python or an experienced programmer eager to delve into game development, this tutorial has something for everyone.

2. Setting up Your Development Environment

Before we dive into the world of Python chess game development, let's ensure you have everything you need to get started.

  • Install Python : If you haven't already, download and install Python from the official website . Make sure to choose the latest stable version.
  • Pygame Installation : Pygame is a powerful library that simplifies game development. You can install it using pip by running the following command in your terminal or command prompt: pip install pygame
  • Code Editor : Choose a code editor that suits your preferences. Popular options include Visual Studio Code, PyCharm, and Jupyter Notebook.

Now that your environment is set up, let's move on to creating our Python chess game.

3. Python Chess Game Tutorial with Pygame

Initializing the chessboard.

In this section, we'll start building the chessboard. We'll create a graphical interface using Pygame and set up the initial chessboard layout.

To kick things off, we'll import the necessary libraries:

Next, we'll initialize Pygame and set up the display window:

4. Full Source Code

5. explanation of source code.

This Python code is for a two-player chess game implemented using the Pygame library. Let's break down the code into its main components and functionalities:

Importing Libraries :

  • The code begins by importing the Pygame library, which is used for creating the graphical user interface of the chess game.

Initializing Pygame :

  • Pygame is initialized using pygame.init(), which sets up the Pygame environment.

Setting Up Game Window :

  • The code sets the dimensions of the game window with a width of 800 pixels and a height of 800 pixels.
  • It also sets the window caption to "Two-Player Chess Game."

Defining Fonts and Clock :

  • Three different fonts are defined for rendering text at various sizes.
  • A clock object (timer) is created to control the frame rate of the game (60 frames per second).

Defining Game Variables and Images :

  • Lists for white and black pieces and their initial positions on the chessboard are defined.
  • Captured pieces for both players are tracked.
  • Variables (turn_step, selection, and valid_moves) are used to manage the game state and player moves.
  • Images for chess pieces (e.g., king, queen, rook) are loaded and scaled to appropriate sizes.

Defining Chess Piece Movement Functions :

  • Several functions are defined to check the valid moves for each type of chess piece (e.g., pawn, rook, knight, bishop, queen, king).
  • These functions return a list of valid move locations for a given piece at a specified position.

Drawing the Game Board :

  • The draw_board() function is responsible for drawing the chessboard grid, status text, and a "FORFEIT" button.

Drawing Chess Pieces :

  • The draw_pieces() function is used to draw the chess pieces on the board according to their current positions.
  • If a piece is selected by a player, it is highlighted with a red or blue rectangle.

Checking Valid Moves and Drawing Highlights :

  • The check_valid_moves() function checks the valid moves for the selected piece and returns a list of valid move locations.
  • The draw_valid() function draws small circles at the valid move locations, indicating where the selected piece can be moved.

Handling Game Events :

  • The code continuously checks for Pygame events, such as mouse clicks and key presses.
  • Mouse clicks are used for selecting pieces and making moves.
  • The "FORFEIT" button can be clicked to end the game.
  • When the game is over, pressing the "ENTER" key restarts the game.

Drawing Captured Pieces :

  • The draw_captured() function displays the captured pieces on the side of the game window for both players.

Checking for Check and Game Over :

  • The draw_check() function draws a flashing square around the king of the player who is in check.
  • The game checks for a checkmate or stalemate condition to determine the winner and end the game.

Main Game Loop :

  • The main game loop (while run:) handles game updates, rendering, and event handling.
  • It also manages the game state, player turns, and the end of the game.

Exiting the Game :

  • The game loop continues until the player closes the game window, at which point Pygame is quit using pygame.quit().

6. Conclusion

In this Python Chess Game Tutorial with Pygame, we've embarked on an exciting journey into the world of game development. From setting up your development environment to implementing advanced features, you've gained valuable insights into creating your own chess game.

Now, it's your turn to bring your creativity and passion to the chessboard. As you continue to refine your game and explore new possibilities, you'll discover the joy of game development and the satisfaction of creating something truly unique.

So, go ahead and start coding your Python chess masterpiece today. The world of chess awaits your innovation and imagination!

Q1. Is Pygame suitable for beginners in game development?

A1. Pygame is beginner-friendly and a great choice for those new to game development. Its simplicity and Python syntax make it accessible.

Q2. Can I customize the chessboard's appearance?

A2. Yes, you can customize the chessboard's appearance by modifying the graphics and colors in your game.

Q3. Are there any online resources for additional chess strategies?

A3. Numerous online resources provide tutorials and strategies to improve your chess skills.

Q4. How can I optimize my Python Chess Game for performance?

A4. Optimizing performance involves efficient coding and minimizing unnecessary calculations. Profiling tools can help identify bottlenecks.

Q5. Where can I find more Pygame tutorials for different games?

A5. You can find a variety of Pygame tutorials on websites, forums, and online courses dedicated to game development.

Q6. Is it possible to add an AI opponent to the game?

A6. Certainly! You can implement an AI opponent using various AI algorithms, such as minimax with alpha-beta pruning. Adding an AI opponent can make your chess game more challenging and enjoyable.

Creator : Avdhesh Varshney

how to convert text to speech in javascript.jpg

That’s a wrap!

I hope you enjoyed this article

Did you like it? Let me know in the comments below đŸ”„ and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks! Faraz 😊

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox, latest post.

Create Sticky Bottom Navbar using HTML and CSS

Create Sticky Bottom Navbar using HTML and CSS

Learn how to create a sticky bottom navbar using HTML and CSS with this easy-to-follow guide.

How to Create a Dropdown List with HTML and CSS

How to Create a Dropdown List with HTML and CSS

August 29, 2024

10 Modern Logo Hover Effects with HTML and CSS

10 Modern Logo Hover Effects with HTML and CSS

August 28, 2024

Create Alert Ticker using HTML, CSS, and JavaScript

Create Alert Ticker using HTML, CSS, and JavaScript

Create Loan Calculator using HTML, CSS, and JavaScript

Create Loan Calculator using HTML, CSS, and JavaScript

August 27, 2024

Create Animated Logout Button Using HTML and CSS

Create Animated Logout Button Using HTML and CSS

Learn to create an animated logout button using simple HTML and CSS. Follow step-by-step instructions to add smooth animations to your website’s logout button.

Create Fortnite Buttons Using HTML and CSS - Step-by-Step Guide

Create Fortnite Buttons Using HTML and CSS - Step-by-Step Guide

June 05, 2024

How to Create a Scroll Down Button: HTML, CSS, JavaScript Tutorial

How to Create a Scroll Down Button: HTML, CSS, JavaScript Tutorial

March 17, 2024

How to Create a Trending Animated Button Using HTML and CSS

How to Create a Trending Animated Button Using HTML and CSS

March 15, 2024

Create Interactive Booking Button with mask-image using HTML and CSS (Source Code)

Create Interactive Booking Button with mask-image using HTML and CSS (Source Code)

March 10, 2024

Create Dice Rolling Game using HTML, CSS, and JavaScript

Create Dice Rolling Game using HTML, CSS, and JavaScript

Learn how to create a dice rolling game using HTML, CSS, and JavaScript. Follow our easy-to-understand guide with clear instructions and code examples.

Create a Breakout Game with HTML, CSS, and JavaScript | Step-by-Step Guide

Create a Breakout Game with HTML, CSS, and JavaScript | Step-by-Step Guide

July 14, 2024

Create a Whack-a-Mole Game with HTML, CSS, and JavaScript | Step-by-Step Guide

Create a Whack-a-Mole Game with HTML, CSS, and JavaScript | Step-by-Step Guide

June 12, 2024

Create Your Own Bubble Shooter Game with HTML and JavaScript

Create Your Own Bubble Shooter Game with HTML and JavaScript

May 01, 2024

Build a Number Guessing Game using HTML, CSS, and JavaScript | Source Code

Build a Number Guessing Game using HTML, CSS, and JavaScript | Source Code

April 01, 2024

Tooltip Hover to Preview Image with Tailwind CSS

Tooltip Hover to Preview Image with Tailwind CSS

Learn how to create a tooltip hover effect to preview images using Tailwind CSS. Follow our simple steps to add this interactive feature to your website.

Create Image Color Extractor Tool using HTML, CSS, JavaScript, and Vibrant.js

Create Image Color Extractor Tool using HTML, CSS, JavaScript, and Vibrant.js

January 23, 2024

Build a Responsive Screen Distance Measure with HTML, CSS, and JavaScript

Build a Responsive Screen Distance Measure with HTML, CSS, and JavaScript

January 04, 2024

Crafting Custom Alarm and Clock Interfaces using HTML, CSS, and JavaScript

Crafting Custom Alarm and Clock Interfaces using HTML, CSS, and JavaScript

November 30, 2023

Detect User's Browser, Screen Resolution, OS, and More with JavaScript using UAParser.js Library

Detect User's Browser, Screen Resolution, OS, and More with JavaScript using UAParser.js Library

October 30, 2023

Creating a Responsive Footer with Tailwind CSS (Source Code)

Creating a Responsive Footer with Tailwind CSS (Source Code)

February 25, 2024

Crafting a Responsive HTML and CSS Footer (Source Code)

Crafting a Responsive HTML and CSS Footer (Source Code)

November 11, 2023

Create an Animated Footer with HTML and CSS (Source Code)

Create an Animated Footer with HTML and CSS (Source Code)

October 17, 2023

Bootstrap Footer Template for Every Website Style

Bootstrap Footer Template for Every Website Style

March 08, 2023

Please allow ads on our siteđŸ„ș

  • All Courses
  • Free Courses
  • Machine Learning with Python
  • Programming
  • Python for Educators
  • Unreal Engine
  • Best Game Engines – Which Should You Use?
  • Unity vs Unreal
  • Unity vs Godot
  • Unreal vs Godot
  • GameMaker vs Unity
  • Construct vs GameMaker
  • Best Game Development Courses (Full List)
  • Programming Language for Games
  • How to Make a Game
  • What is Unreal Engine?
  • How to Make a VR Game
  • How to Make an HTML5 Game
  • What is Phaser?
  • Roblox Game Making Tutorials
  • What is Unity?
  • How to Make a Unity Game?
  • How to Make a Mobile Game in Unity
  • Unity Multiplayer Tutorial
  • Unity RPG Tutorial
  • Unity Animator Tutorial
  • Unity Certification
  • Unity Platformer Tutorial
  • Procedural Generation
  • What is Godot?
  • Best Godot Online Courses
  • Best Godot Tutorials
  • Complete Guide to GDScript
  • Godot RPG Tutorial
  • Godot Collision Detection
  • What is Python Programming?
  • How to Learn Python?
  • Best Python Courses – Complete List
  • Complete Guide to Python Enums
  • Generative AI in Python
  • Python Turtle Tutorial
  • Why Learn Coding?
  • What is Programming?
  • How to Learn Coding for Free
  • The Best Way to Learn to Code – 10 Steps
  • Beginners Coding Success Guide
  • Code Editor Comparison
  • How to Code a Game
  • Complete Guide to C#
  • Create Free Account

aa Pygame Examples Tutorial Complete Guide - Pygame Examples Tutorial - Complete Guide

Pygame Examples Tutorial – Complete Guide

Escaping into the world of games is a treat many enjoy but have you ever wondered about the sheer joy and satisfaction of creating your own game? This notion can seem daunting, especially if you’re new to programming, but python’s Pygame library comes to the rescue. It offers an excellent platform to not just dip your toes but also hone your skills in game creation, no matter your level of expertise. So let’s dive straight in!

Table of contents

What is Pygame?

Pygame is an open-source module of Python used for game creation. It’s built over the highly powerful SDL library and simplifies game development, making it accessible to coding novices and facilitating the learning process.

Why Pygame?

Often, beginners find themselves bogged down by complex syntax and rules when they begin coding. Pygame changes that with its simplicity and straightforwardness.

More so, with Pygame, not only can you create games but also multimedia applications. It’s a tool with vast applications!

The Allure of Pygame

Learning Pygame equips you with the ability to create simple 2D games, and as you grow, the possibilities become endless. It puts you in the driver’s seat of your game creation journey, offering an exciting creative outlet while you learn and grow as a programmer .

Moreover, Pygame stands as a stepping stone toward more advanced game development frameworks, making learning it a valuable long-term investment for those interested in game development.

CTA Small Image - Pygame Examples Tutorial - Complete Guide

Setting up Pygame

The first thing we need to do to use Pygame is to install it. Run this command in your terminal:

Creating a Pygame Window

Once the installation is complete, try creating a simple Pygame window. Let’s start by importing Pygame and initiating it:

Now, let’s create a display:

This will create a window of width 500 and height 500. Note that the dimensions are passed as a tuple.

Running a Pygame Window

The following snippet runs a Pygame window until it is manually closed:

This loop runs indefinitely, until we manually close the window. The delay function ensures that the loop does not run too quickly, and pygame.QUIT helps in handling window closing events.

Drawing on the Window

Let’s take it a step further and draw a rectangle on this window:

The draw.rect function takes the window on which to draw, the color of the rectangle in RGB format, and the rectangle characteristics (x and y coordinates, width, and height). Finally, we update the display to reflect the drawn rectangle.

Moving the Rectangle

Now, let’s get our rectangle moving. For this, we’ll introduce a few extra variables and modify our game loop:

Here, vel defines the velocity or speed of our rectangle. To make our rectangle move, we need to capture the user inputs and accordingly alter the rectangle’s position:

This code checks which arrow key is pressed and accordingly increases or decreases the x or y coordinate of the rectangle, moving it in the appropriate direction.

Adding Boundaries

Currently, our rectangle can move off-screen. To prevent this, we’ll add a few conditions:

These conditions check if the rectangle is within the boundaries of our window before allowing it to move.

Loading and Displaying Sprites

Now, let’s go further by introducing a sprite to our game. First, we load the sprite:

Next, we display the sprite in our window, replacing the rectangle:

The blit function draws our sprite at coordinates (x, y).

Adding Music and Sound Effects

Finally, a game is incomplete without some sound effects and background music. Load a sound effect and play it:

To play background music, use the music.load method:

The argument -1 will loop the music indefinitely.

Handling Sprite Collision

For a more interesting gameplay, let’s introduce collision detection. To do so we will consider each sprite as a rectangle and check if these rectangles overlap.

Here, colliderect() checks if one sprite’s rectangle has collided with the other’s. We can display or trigger certain events if a collision occurs.

Controlling Sprite Animation

Our sprite may have multiple frames for animation. To display these animations, we need to cycle through them in our game loop:

We load all frames of the sprite into a list. Then, we display each frame every third loop cycle by using integer division. The modulo operation ensures frame_count doesn’t exceed 8 and loops back to 0.

Creating Background Images

Moving on, to create a background for your game, load an image and blit it before drawing our sprite:

Creating Parallax Backgrounds

Parallax backgrounds create a sense of depth. Let’s implement this:

Two identical images are moved leftwards to create the illusion of motion. As soon as one image goes off screen, it is repositioned at the right end resulting in a seamless transition.

Adding Text to Your Game

Finally, let’s add some text to our game. Pygame allows us to use system fonts or load our own.

This code centers the text on the window. The font.render() method creates a surface that can then be drawn onto our window.

So there you have it! With these tools and knowledge, you can start creating your own simple 2D games using Pygame. Immerse yourself in this world of creativity and endless possibilities!

Continuing Your Journey

You’ve made it this far and are now equipped with the initial skills needed for game creation with Pygame! But don’t stop here. Coding, like any other skill, is honed and perfected with practice. Engaging oneself in a variety of projects will ultimately provide a comprehensive understanding and proficiency in Python and game development.

At Zenva , we are committed to providing you with the opportunity to continue your journey. We offer a broad range of beginner to professional courses in programming , game development and AI, with over 250 supported courses for you to delve deeper into topics you are passionate about. One of our flagship offerings is the Python Mini-Degree , a comprehensive and flexible collection of courses that covers essential Python programming topics, as well as more specialized subjects such as game development, AI chatbots, data science, and machine learning.

Moreover, check out our broader collection of Python courses that cater to a wide range of interests and skill levels. Remember, learning coding is a marathon, not a sprint. So keep going, and happy coding!

Embarking on a journey with Pygame not only provides a stepping stone towards game development but also promises an exciting venture into a world defined by creativity and logic. As a beginner or an avid programmer looking to spread their wings, Pygame offers an inviting platform to dive headlong into the world of making games, animations, and even multimedia applications. Crafting games, after all, isn’t just about the end product; the journey is where the real learning and excitement lies.

We at Zenva invite you to continue this thrilling adventure. Our Python Mini-Degree offers a comprehensive and in-depth coverage of Python and its various applications, providing the perfect platform for you to explore and elevate your skills. So grab your keyboards and immerse yourself in this fascinating journey of creation!

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

Python Blog Image - Pygame Examples Tutorial - Complete Guide

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.

Continue Learning

How to Code Games in Pygame - Best Learning Tutorials

File Download Link

 alt=

Send me a download link for the files of .

Video Game Design and Development

Encouragement, advice, and support for aspiring game designers.

Python Game Development Tutorials Online

Learn to program games with phyton

Python is a simple language to start with, and if you’re looking for a quick win in your quest to master all coding languages (the Ultimate Quest!), Python is a good place to start.

To get any value out of the game-making side of Python tutorials, you need to first be familiar with some core concepts of Python. The best way to learn those is through the more mundane functions of Python. By mundane we just mean not relating to games.

We’ve compiled a list of the most useful Python tutorials. This list includes those that teach basic Python elements and those that guide you on a game-building journey.

It helps if you know some programming language before diving into game-making, even if it isn’t necessarily the Python language . Don’t be scared, though. As you go through these tutorials, you will consistently see claims toward how easy Python is to use.

To make games with the Python language, you’ll end up using PyGame. Like we said earlier, some of the tutorials we’ve put together here include tutorials just for Python.

These are best if you have no coding or programming language experience. We recommend learning Python before jumping to PyGame because it will likely make your passage to competency a much smoother one.

If you’re a quick learner and you’ve done programming before (and don’t like listening to our advice, apparently), you could probably manage the challenges in PyGame game development. If it’s too hard, you can always rain check your PyGame lessons and hit the Python introductory tutorials.

Ultimately, the choice is yours. Mastering programming languages don’t need to be a sprint. If you think long-term, you’ll realize you have time to do it all. Take it one piece at a time, and absorb the language.

The following courses are ranked by Beginner to Expert level:

5 Courses for Python Game Development

Udemy python programming.

If you don’t mind dropping 50 bones (see: $50) and watching close to ten hours of the instructional video, this on-demand course over at Udemy could be your fast track to Python success.

It’s a great way to learn the basics if you need video-driven lessons. The free stuff on YouTube isn’t quite as powerful for Python as it is for some of the other programming languages and software out there.

With an average of 4.6 stars across over 3,000 reviews, we’re talking about some high-quality programming. If you’re devoid of any prior programming experience, this course is your ticket into the great unknown. It’ll start you at the very beginning–you don’t even need to have Python downloaded yet.

You might notice this course shares the same title as one of the books previously mentioned. That’s because it’s the same guy, Al Sweigart. It’s hard to find better tutorial material than the stuff Sweigart puts out. Even the official Python pages link to some of his content.

If you liked his free written content, but want his video guidance to help things click, then grab this course. If you don’t like it, you have a 30-day money-back guarantee. That means you can take it for a spin and ditch it if it’s no good. We’re big on minimizing risk over here.

A month gives you plenty of time to get through at least a few hours of the program and decide if you want your fifty bucks back or access to the program for life.

python programming instructions visual

Python for Beginners

As is the trend for most game design software companies, Python offers tutorials for its development program. These tutorials can help whether you’re just starting or you’ve been entrenched in Python for a while now.

If you’re new to Python, but not new to programming, your best bet is to start with Python for Beginners. If you’re completely new to programming, Python has you covered with a non-programmer Beginner’s Guide, just for you.

The “ standard ” Python Guide introduces you to some of Python’s most noteworthy features (not all of its features). The tutorial itself even says that the tutorial is far from comprehensive.

After reading the tutorial you’ll be able to get started using Python. You will likely want to continue exploring the Python database (or other tutorials on our list!) to level up your Python capabilities.

LearnPython

This program is neat, and not just because it comes with its own Facebook group. This FB group is good because it acts as a “help and advice” forum for people using Python .

This tutorial isn’t specifically game-related, but that doesn’t mean you won’t find it useful. Learning all the tricks for the software, even those outside of what you think you’d need for game development, is a good way to develop your Python problem-solving skills.

The LearnPython site has introductory tutorials for those new to Python. It also has more advanced tutorials, which can help those of you who’ve been kicking around with Python for a bit already.

If you’re looking for knowledge surrounding the broader application of Python , this is a good tutorial to spend some time with.

Think Python: How to Think Like A Computer Scientist

If you need to get down to the brass tacks of all-things basic Python, this web-based, text-based guide could be just the thing.

We want to tell you something upfront about this: This guide is thorough.

You can buy the tutorial at amazon.com, but it’s provided for free online. We’ll link to it again here.

This guide starts with topics like breaking down the differences between high-level and low-level languages. If you have no programming experience, you will not be left in the dust. If you have some programming experience, you might find the extra explanations tedious to get through (at least in the early parts of the tutorial).

The guide continues through the Python programming language topics, explaining elements like variables, expressions and statements, functions, interface design, conditionals and recursion, classes and functions, and the list goes on. It’s a long guide. A thorough guide.

The tutorial also includes some exercises for you to practice, prompting you to write different programs and different functions.

All in all, it’s a very helpful guide for getting up-to-speed with Python. It’ll provide a helpful, stable base from which you can build your Python game-designing skills.

Invent With Python

If you don’t mind some “light” PDF reading, this 365-page tutorial , Making Games with Python and PyGame, could be just the thing to get you started making games with Python .

This particular book is for the intermediate programmer. If you have some experience programming, especially with Python , but don’t know how to use your knowledge to make games, then this is exactly the right tutorial for you.

The Making Games book uses game examples from the PyGame library to teach you how to make similar games. The goal of this tutorial is to give you a whole new batch of ideas for using Python software to develop your games. So even if you know Python and PyGame but you need ideas, you could give this book a skim.

If you don’t know anything about the Python language, have no fear. Invent with Python has other options for you. You can use this second tutorial to automate some basic computer tasks using Python, which is a good way to learn the language (and also automate tasks!).

They also offer “Invent Your Own Computer Games with Python”, which gives you source codes for completed games and teaches the concept using the provided source code examples. All three books are good options for you, depending on where you are in your programming.

All three of these books are offered for free online, or you can buy a physical copy through Amazon (in exchange for money). There’s even a subreddit for Invent with Python (it’s no Facebook group, but
), you can engage with other Python users who’ve read these books while you go through them yourself.

More Python Development Courses

Flatiron school.

The Flatiron School offers programs and, more importantly, valuable certifications for graduates of Python courses. For those who are strongly career-minded, the Flatiron school has an employment rate of 93% and an average salary of $76,000 for its graduates. With courses like UX/UI design, software engineering, and data science, your knowledge of programming mixed with these existing courses will only bolster your skills with Python.

Learn more…

Data Camp offers many different courses in Python. Starting with beginner courses, Data Camp covers all of the bases. With multiple classes, hands-on instruction, and examples, Data Camp is offering arguably the best way to learn Python. The instructors are veteran programmers who can instruct you on better ways to use programming in a matter of hours.

Pygame for Python

Python is a coding language celebrated throughout the programming and software engineering communities for being a stable language. People consider it a lot easier to learn than some other programming languages, like the C languages, C++ and C#.

That’s why developing games using Python, and its extension PyGame, is naturally becoming more commonplace.

How to Use PyGame

Pygame, Python’s set of guides and modules for gaming, is an excellent place for aspiring game developers to start their coding and game development journey.

How to Install Pygame

Before you install Pygame, you’re naturally going to need Python to get started. You can download Python straight from the official site.

Once you have Python installed on your system, it’s time for the Pygame install.

The best way to install PyGame is with the assistance of pip, the Python package installer. This makes installing various aspects and modules from PyGame a whole lot easier.

If you need further assistance in installing Python, check out the official documentation.

In general, you’re going to enter the following: ‘python -m pip install SomePackage.’ However, specifically for PyGame, you’re going to put ‘python3 -m pip install -U pygame –user’

Pygame Fundamentals

The main fundamentals of PyGame are crucial for understanding it as a game development tool. Everything you do takes place on the surface. To fill the surface, type in screen.fill() to fill the background.

Next, we have what we call ‘blitting.’ This is the process of rendering the game objects. You ‘blit’ the object, and it renders it onto the screen.

Then we have the event loop. This is how your game actually runs. This puts your game on a loop until you determine when you exit the loop.

Drawing Objects

This is a massive part of the PyGame process. You’re going to want to enter ‘pygame.draw.’ This allows the user to draw various shapes on a surface. Let’s look at some options you have.

  • Pygame Draw Line
  • Pygame Draw Circle
  • Pygame Draw Rectangle

Working with PyGame Sprites

Sprites, as you may know, are pixels brought together to create a picture, character, or animation. Luckily, you can use sprites within PyGame.

Game Development 1-2: Working with Sprites

pygame.sprite.Sprite.__init__(self)

Which opens PyGame’s sprite module. From here, you need to describe your dimensions of the object. If you’re creating a blue rectangle, you’d type in:

class Player(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((50, 50)) self.image.fill(BLUE) self.rect = self.image.get_rect() self.rect.center = (WIDTH / 2, HEIGHT / 2)

Pygame Tutorials

Here are a few excellent tutorials for Pygame. These are various tutorials ranging from beginning modules to more complex projects like creating your first, more basic game.

  • Pygame Tutorial for Beginners – Python Game Development Course – Pygame Tutorial Python 3
  • Pygame Tutorial | Python Pygame | Intellipaat
  • PyGame Tutorial | PyGame Python Tutorial For Beginners | Python Certification Training | Edureka
  • Pygame Tutorial #3 – Character Animation & Sprites
  • Python Pygame Zelda Game Tutorial for Beginners

Depending on the game, Python, and by extension, Pygame, can be a fantastic asset towards creating games. With these tutorials, you’ll be able to install Pygame and get the hang of a more simple game creation process than another programming outlet.

Whichever you choose to use in PyGame, you’ll hopefully get a good grip on game development, and you can master Python as a coding language.

20 Games Made with Python

Mount & blade 2.

Mount & Blade is a pretty straightforward single-player game that makes it feel truly historical, even though it’s based on fiction. It uses Python scripts as part of its module system. Players have to guard against new kingdoms rising against it while the empire is ravaged by civil war.

Using StacklessPython, Eve Online is a community-driven game where players get to choose their own path in space explanation. The server and the client program used Stackless Python, which is a variation of the Python programming language.

Pirates of the Caribbean

Disney’s Pirates of the Caribbean game used Python and C++ scripting to develop this exciting video game based on the popular ride and movies.

Even though it has ported to other languages, the original Galcon was written using Python.

Similar to its predecessors, Sims 4 is a life simulation video game that has been incredibly popular for years. Module support was prepared using Python as was some of the application coding.

Civilization IV

Also known as Sid Meier’s Civilization IV, it’s the fourth version of the Civilization game franchise, this one develop by Soren Johnson. Launched in autumn, 2005, the map editor of the game supports Python.

Frets on Fire

This popular Finnish music video game allows players to earn points by hitting notes that would pop up on the screen, much like Guitar Hero.

World of Tanks

Created by the company Wargaming, World of Tanks featured World War II and early Cold War battle vehicles. It is free to play, but players are able to use premium features for a fee. The game uses Python as its focus for scripting language.

Toontown Online

Disney’s Toontown Online is a three-dimensional multiplayer online role-playing game based on a cartoon animal world. Developers utilized Python for writing codes. Panda3D was utilized for the graphics.

Battlefield 2

Using clear text Python scripts, Battlefield 2 uses some of the game logic with Python. Originally designed by Digital Illusions CE in 2005, Battlefield 2 is a military simulator first-person shooter game.

Conqueror of Empires

This strategy game allows up to four players to battle for victory, expand empires, conquer cities, and attack enemies.

Bloons Tower Defense

Written in Python, this game allows players to try and keep balloons from reaching the end of a course. Pop balloons and complete levels to earn “money.”

Snake Pygame

This basic version of a snake game has players moving forward with the trail left behind that looks like a moving snake. If you hit the border of the screen or the snake’s tail, you lose.

Asteroids Escape

Avoid various obstacles in space to try and reach your destination. Avoid the asteroids, even as they explode, fragmenting and creating more havoc in your path.

Alien Invasion Game

Using the Pygame Module of Python, it only requires basic knowledge of Python to really understand the game and how it works and was developed.

The legendary oriental action game Metin 2 pits players against dragons and demon lords. Built using a version of Pygame.

The original title of Severence was Blade: The Edge of Darkness and used Python for nearly every aspect of the game, built in C, although the graphics were built in another language.

Test your abilities and learn new skills in this game built using Python.

This arcade-style game takes place in outer space. The player needs to maneuver around various obstacles to follow a certain path to victory.

Try escaping the evil bullet up on platforms, and you’ll be playing Duckjump, developed with Python.

Is Python good for video games?

Python is readable and offers a clean syntax structure, so yes, it is good for video games, and is often considered faster for game development than in Java.

Is it hard to learn Python?

Depending on your dedication level to learning new things and programming, Python has varying degrees of difficulty. If you are an individual who has trouble with programming, Python may be more complicated than for those who are more computer science-minded. I guarantee the best way to learn Python is through the tutorials we have listed.

What is the best website to learn Python?

Overall, the best website to learn Python is from Udemy. Udemy offers users (for a nominal fee), valuable visual aids, and videos that truly make the process of learning Python more accessible and more comprehensive.

Udemy is perfect for beginners not only with Python but programming in general. If you are totally in the dark regarding the ins and outs of programming, Udemy will help you out on your journey to learn Python. No doubt, outside of the official documentation, Udemy is the best way to learn Python.

Which certification is best for Python?

Various certifications help with specific fields, all depending on where you receive it. The number one certification is one you receive from the University of Michigan.

This certification focuses on data and analyzing the data using Python. It has fantastic reviews from former students and earns you a certification in Python after learning in 5 courses. Lectures are interactive and hands-on, something that is key to learning something like Python.

The University of Michigan offers the best way to learn Python for a certification. Some of the courses deal with starting with data, data structure, using databases with Python, and accessing data with Python.

Can I learn Python in 6 months?

Absolutely!

With the resources offered in many different locations, both physically and remote, you could learn Python in 6 months. Of course, other factors come into play, like your propensity and preexisting knowledge of coding, Those with a talent for coding could learn Python quickly but fret not if you’re starting out.

Six months is a reasonable time estimate. However, we recommend taking longer to understand and utilize Python fully. The best way to learn Python is by making it slow and learning basics, so you have a foundation to build upon.

Popular Posts

unreal game engine tutorial guide

About Dustin Tyler

Initially focused on web dev, Dustin was introduced to game design by a friend after college and was immediately attracted to the combination of technical skill and creativity required to make an awesome game.

He’s utilized his web dev skills and desire to help others by creating a resource where expert game designers can share what they’ve learned with the next generation of aspiring game makers.

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • How to Use Animation Storyboards
  • What is Cel Shading & How to Use It?
  • The Role of Computer Science in Video Games
  • How to Start Keyframing in Animation
  • Cite this Website
  • California Consumer Privacy Act
  • Editorial Guidelines

DMCA.com Protection Status

  • Game Design Education
  • Game Design Careers
  • Game Engines
  • Learn Skills
  • Ask an Expert
  • Graphic Design
  • Free Mini-Courses
  • Our GameMaker Course

Send us mail:

Lake House Media 7910 4TH ST N STE 300 ST. PETERSBURG, FL 33702

Tic-tac-toe using Python

Tic Tac Toe Featured Image

In this article, we will be going through the steps of creating Tic-tac-toe using Python Language from scratch.

About the game

Tic-tac-toe is a two-player game, that is played on a 3×3 square grid. Each player occupies a cell in turns, with the objective of placing three marks in a horizontal, vertical, or diagonal pattern. One player uses cross 'X' as his marker, while the other uses a naught 'O' .

Step 1: Tic-tac-toe Design

We will be playing Tic-tac-toe on the command line, therefore, the first thing we have to do is create a design for our tic-tac-toe.

Design

If a player has to mark a particular box, he must enter the corresponding number shown in the grid. Suppose, we wish to occupy the center block, then we will input 5 in the terminal. This grid can be generated by:

In the code above, the function creates our tic-tac-toe game according to the values delivered as an argument. Here the argument, values is a list containing the status of each cell in the grid.

Step 2: Store information using data structures

The core of any game is the game mechanics behind it. Since this is a fairly easy game to create, the mechanics involved are simple too.

At any instant of time, we need two crucial information:

  • Status of the grid – We must have a data structure that stores each cell’s state, that is, whether it is occupied or vacant.
  • Each player’s moves – We must somehow have the knowledge of each player’s past and present moves, that is, the positions occupied by 'X' and 'O' .
Note: Both the information could have been accessed using the status of the grid, but it would have required to traverse it every time we need the player’s positions. This can be called as time vs. space complexity trade-off. It is a general technique to conserve time.

Status of the grid is managed by a list of characters, which can have three possible values,

  • ' ' – A vacant cell
  • 'X' – A cell occupied by player X
  • 'O' – A cell occupied by player O

Each player’s moves are stored as a dictionary of a list of integers. The keys are 'X' and 'O' for the respective player. Their corresponding lists contain the numbers given to the grid cells, they occupy.

Note: The variable cur_player , stores the current player making the move, as in 'X' or 'O' .

Step 3: Game Loop

Every game, has some kind of game loop, which runs until some player wins or the game ends in a draw. In tic-tac-toe, each loop iteration refers to a single move any player makes.

Step 4: Handle player input

In every game iteration, a player must input his move.

We create a try block, in case a player enters some unintended value. Such an event must not stop the game, therefore, we handle the exception of ValueError and continue with our game.

We need to perform some sanity checks, like value entered is a valid position and if it is a valid position, is it already occupied?

Step 5: Update information

According to the player input, we need to update the information for the smooth functioning of the game.

The values list updates the cell occupied according to the current player. The player position adds the position just taken by the current player.

After updating the values list and calling the print_tic_tac_toe() function, the grid looks like this:

Update After Turn

Step 6: Check win or draw

After each move, we have to check whether any player won the game or the game has been drawn. It can be checked by:

Function Calls:

If any player wins, then the single_game() function returns the current player, who made the move. In case, the game is drawn, 'D' is sent back.

check_win() – The function has all the winning combinations. All it does is, it checks whether any of the winning combinations is satisfied by the current player’s positions. If it does, it returns True . If none of the combinations is satisfied, then the function returns False .

check_draw() – The draw condition is fairly simple, as the game is drawn when all ‘nine’ positions are taken.

Step 7: Switch the current player

Since each player only moves once at a time, therefore after every successful move, we have to swap the current player.

As far as a single game is concerned, this is all we need to do. But this article also presents a scoreboard system for keeping track, if the players want to play multiple games.

Step 8: Enter player names

It is mandatory for any scoreboard to display each player names.

Step 9: Store game-related information

The information like the current player, the choice of players (take cross or naught), the available options (cross and naught), and the scoreboard need to be stored.

By default, the current player is the player who entered the name first.

Step 10: Design scoreboard

The scoreboard is stored as a dictionary, where keys are the player names and values are their win number.

To display the scoreboard, we need the player names. The keys are extracted using .keys() function and then converted to list, so that it can indexed while displaying the scores.

Step 11: Outer Game Loop

We need another game loop, for managing multiple matches of Tic-tac-toe. Each match, the current player chooses his mark ( 'X' or 'O' ). The menu for choosing must be displayed in every game iteration:

The scoreboard and menu look like this:

Score Board Menu

Step 12: Handle and Assign Player Choice

Each iteration, we have to handle and store current player’s choice.

According to the player’s choice, the data has been stored. This is important since after each game finishes, it will tell us which player won.

Step 13: Execute the match

After storing all the necessary information, it is time to execute an independent match and store the winning mark.

Step 14: Update the scoreboard

We need to update the scoreboard after each match of Tic-tac-toe.

If the game has not ended in a draw, then we update the scoreboard.

Step 15: Switch the choosing player

It is a generous idea, that each player must have the opportunity to choose which mark they want. To do so, we swap the value in cur_player .

Complete Working Code

Time for a gameplay.

All the steps to create the game has been finished. Now is the time to play the game.

We hope that this article was fun as well as informative to the reader. I’ve also uploaded the code on Github. You can visit here for the code. If there are any suggestions for the game, feel free to comment.

How to Create a Text Based Adventure Game in Python

4

Your changes have been saved

Email is sent

Email has already been sent

Please verify your email address.

You’ve reached your account maximum for followed topics.

These Photography Rules Leveled Up My Smartphone Photos

Why i prefer shooting street photography on my smartphone over a dslr, fake cpus are on the rise, and this is how you spot one.

A Python text-based adventure game is a fun project you can undertake if you are learning how to program. You can make a text adventure game using Python, run it in a command line, and change the story based on the text that the player enters.

The Python script for a Python adventure game will cover several kinds of fundamental programming concepts. This includes print statements, if statements, and functions.

How to Create the Python Script for the Text Adventure Game and Add Story Content

You can make a text-based adventure game in Python by creating a script using a standard text file with a .py extension. If you are not familiar with Python syntax, take a look at some basic Python examples that may help you learn it faster .

You can download the full source code for the Python adventure game from this GitHub repository .

You can also look at other useful Python one-liners to perform certain tasks, before starting on the Python adventure game.

In the main function of the Python file, set up your story and welcome message.

  • Create a new file called "AdventureGame.py", to store the code for your Python adventure game.
  • In the file, add the main starting function. The function will include a brief opening story to welcome the player to the Python text-based adventure game. It will then call another function called introScene() . if __name__ == "__main__" :    while   True :      print ( "Welcome to the Adventure Game!" )      print ( "As an avid traveler, you have decided to visit the Catacombs of Paris." )      print ( "However, during your exploration, you find yourself lost." )      print ( "You can choose to walk in multiple directions to find a way out." )     print("Let's start   with your name : ")     name = input()      print ( "Good luck, " +name+ "." )     introScene()

How to Create Multiple Scenes and Options in the Story for the Python Adventure Game

The story for the text-based adventure game will contain several scenes or "rooms". You can create a function for each scene of the Python adventure game so that you can re-use it later if the player ends up entering the same room again.

Each scene will also have different choices of where to go. It is a good idea to map out your story before coding the scenarios, to make sure the story for your text-based adventure game is well organized.

Map of storyline in Python game

Each scene for the Python text game will have a list of valid directions, and an if-statement for the multiple paths the player can take. Depending on the path the player takes in your Python adventure game, the script will call the next scene.

Create functions for the scenes that will occur in your Python adventure game.

  • Create the introScene() function above the main function. Add a message and the directions that the player can walk in. def   introScene () :   directions = [ "left" , "right" , "forward" ]    print ( "You are at a crossroads, and you can choose to go down any of the four hallways. Where would you like to go?" )   userInput = ""    while userInput not in directions:      print ( "Options: left/right/backward/forward" )     userInput = input()      if userInput == "left" :       showShadowFigure()      elif userInput == "right" :       showSkeletons()      elif userInput == "forward" :       hauntedRoom()      elif userInput == "backward" :        print ( "You find that this door opens into a wall." )      else :        print ( "Please enter a valid option for the adventure game." )
  • Depending on the user's input, your Python adventure game will call another scene. For example, if the player types "left", the adventure game will display the scene showShadowFigure() to the player. From this room, if the player goes backward, the Python adventure game will take them back to the intro scene. If they go left or right, they will either enter another room or hit a dead end. def   showShadowFigure () :   directions = [ "right" , "backward" ]    print ( "You see a dark shadowy figure appear in the distance. You are creeped out. Where would you like to go?" )   userInput = ""    while userInput not in directions:      print ( "Options: right/left/backward" )     userInput = input()      if userInput == "right" :       cameraScene()      elif userInput == "left" :        print ( "You find that this door opens into a wall." )      elif userInput == "backward" :       introScene()      else :        print ( "Please enter a valid option for the adventure game." )
  • Add the camera scene to handle the case where the player turns right. This is where they can find one of the exits. Call the quit() function to end the Python text-based adventure game. The player can also still choose to move backward to the previous scene. def   cameraScene () :   directions = [ "forward" , "backward" ]    print ( "You see a camera that has been dropped on the ground. Someone has been here recently. Where would you like to go?" )   userInput = ""    while userInput not in directions:      print ( "Options: forward/backward" )     userInput = input()      if userInput == "forward" :        print ( "You made it! You've found an exit." )       quit()      elif userInput == "backward" :       showShadowFigure()      else :        print ( "Please enter a valid option for the adventure game." )
  • Back to the beginning of the adventure game, you will still need to add the functions for the remaining scenes. Add the hauntedRoom() scene for the case where the player chooses to move forward. This will also end the Python adventure game depending on the player's choice. def   hauntedRoom () :   directions = [ "right" , "left" , "backward" ]    print ( "You hear strange voices. You think you have awoken some of the dead. Where would you like to go?" )   userInput = ""    while userInput not in directions:      print ( "Options: right/left/backward" )     userInput = input()      if userInput == "right" :       print("Multiple goul-like creatures start emerging as you enter the room. You are killed. ")       quit()      elif userInput == "left" :        print ( "You made it! You've found an exit." )       quit()      elif userInput == "backward" :       introScene()      else :        print ( "Please enter a valid option for the adventure game." )
  • You can also add more interesting content to your Python text-based adventure game. Create a global variable, at the very top of the file, called "weapon". It will either be true or false depending on if the player finds it. weapon = False
  • In one of the rooms, set the weapon variable to true if the player finds it. The player can use it in the next room if needed. def   showSkeletons () :   directions = [ "backward" , "forward" ]    global weapon    print ( "You see a wall of skeletons as you walk into the room. Someone is watching you. Where would you like to go?" )   userInput = ""    while userInput not in directions:      print ( "Options: left/backward/forward" )     userInput = input()      if userInput == "left" :        print ( "You find that this door opens into a wall. You open some of the drywall to discover a knife." )       weapon = True      elif userInput == "backward" :       introScene()      elif userInput == "forward" :       strangeCreature()      else :        print ( "Please enter a valid option for the adventure game." )
  • If the player finds the weapon, they can kill the enemy in the next room, and find another exit. Otherwise, the enemy will kill them. def   strangeCreature () :   actions = [ "fight" , "flee" ]    global weapon    print ( "A strange goul-like creature has appeared. You can either run or fight it. What would you like to do?" )   userInput = ""    while userInput not in actions:      print ( "Options: flee/fight" )     userInput = input()      if userInput == "fight" :       if weapon:         print("You kill the goul with the knife you found earlier. After moving forward, you find one of the exits. Congrats! ")        else :          print ( "The goul-like creature has killed you." )       quit()      elif userInput == "flee" :       showSkeletons()      else :        print ( "Please enter a valid option for the adventure game." )

How to Run the Python Script for the Text-Based Adventure Game

You can run the script for your Python text-based game using a terminal or command prompt. As you enter input into the terminal, the story will continue to move forward to the next scene of the Python adventure game.

  • Using a terminal or command prompt, navigate to the location where you stored the file for your Python adventure game. cd C:\Users\Sharl\Desktop\Python
  • Run the script to start your Python text-based adventure game. python   AdventureGame .py

Python Adventure Game in command line

Create a Simple Text-Based Adventure Game Using Just One Python Script

You can create a Python text-based adventure game using a Python script, and run it on a command line. Inside the Python adventure game, you can present the player with a welcoming message and initial story. The player can then type in their actions based on the options you present within the Python adventure game.

If you want to become a more well-rounded Python developer, there are other projects you can make other than a text-based adventure game. You can have a look at some of the useful tools that you can use or integrate with Python.

  • Programming
  • Game Development
  • Python Course
  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries

Balloon Archer game in Python using the Pygame module

Balloon Archer is a 2D game where the player uses a bow and arrow to pop balloons that float across the screen. The main theme of this game is to shoot down the balloons using arrows and on each successful attempt, the player earns a point and on each unsuccessful attempt, the player loses a life. If the player loses all 5 lives, then it’s GAME OVER!

The player stands on the left half of the screen and must shoot the balloons that go upwards from bottom to top on the right half of the screen. If the arrow goes off the screen without hitting any balloons, then life is deducted. The player must navigate the archer to aim perfectly. This article will cover how to create such a game in Object Oriented Programming style (OOP) in  Python .

Balloon Archer Game in Python

The Balloon Archer game has the following rules:

  • The player controls the archer’s movements using the arrow keys. The archer can move left, right, up, and down within the specified constrained region.
  • The player can shoot the arrows using the spacebar. The arrows move horizontally from left to right.
  • The player’s score increases by one for each successful balloon hit.
  • If an arrow goes off the screen without hitting any single balloon, the player loses a life.
  • The goal is to achieve the maximum score possible before running out of lives.

Balloon Archer Game Controls

The Balloon Archer game can be played in Python using keyboard controls. These controls are as follows:

  • Use left/right and up/down arrows to move the archer
  • Use the space bar to shoot the arrow
  • Use ‘r’ or ‘q’ to restart or quit the game

Functionalities of Balloon Archer Game in Python

The implementation of the balloon archer game using the Pygame module is divided into 6 parts. We will see the stepwise implementation of the game for a better understanding.

Initial Setup

Here, we initialize the module and define all the necessary global variables that are required all over the game. We will install the Pygame module for defining the colors, FPS, font, dimensions of the screen, etc, and the random module to randomly display the balloons on the screen within a specified region.

The pygame.init() method is used to initialize the necessary modules. Then we used the pygame.font.Font() method to create a font object and pass the font file and the size of the font as the parameter. The pygame.display.set_caption() method is used to set the title of the Pygame window. It set the title as whatever string is provided in the parameters. Then pygame.time.Clock() method is used to create a clock object to keep track of time.

    

The Helper Functions

The helper functions are user-defined functions that are used by the game manager. The populateBalloons() function is used for generating balloons at random positions on the right half of the screen. It takes in the balloons’ width, height, and speed, counts them, and spaces them accordingly. The ‘listOfBalloons’ Python List stores the list of randomly generated balloons.

The gameOver() function is called when the player runs out of all the lives. This function asks for the player’s input to restart or terminate the game. If the player presses ‘r’, then the game restarts, and if the player presses ‘q’, then the game is terminated. The font.render() method is used to render the text on a surface object. The screen.blit() method is used to draw the surface on this surface. It takes the rendered text and its size as parameters.

The next is event handling in Pygame . In this game, we will be using keyboard events only to play, quit, shoot arrows, and move up or down and right or left. The pygame.event.get() returns a list of current events. We are using the following event in this section:

  • pygame.QUIT: used to quit the Pygame window
  • pygame.KEYDOWN: detects if a keyboard key is pressed or not
  • pygame.K_r: checks if “r” key was pressed or not
  • pygame.K_q: checks if “q” key was pressed or not

The pygame.display.update() method as the name suggests, is used to update the content of the Pygame window.

 

The Archer Class

This class consists of all the methods needed to control the player. We first initialize the data members of the class, i.e., height, width, and speed. The pygame.transform.scale() method is used to change the size of the image. We will be using the “archer.png” image. The pygame.get_rect() method returns the rectangular object of the image. The position of the archer is controlled using the “archerRect”.

game assignment in python

The display() function displays the transformed image on the screen whereas the update() function updates the archer position on the screen based on the xFac and yFac variables. These variables are obtained based on the key pressed by the user. This method also prevents the player from moving beyond the left edge and the center of the screen and contains the player’s position to the left half of the screen. If the player presses the up/down arrow keys, then the value of yFac will be -1/1, and only the Y component of the player is changed. If the player presses the left/right arrow keys, then the value of xFac will be -1/1, and only the X component of the player will be changed.

The Balloon Class

This class consists of all the methods needed to control the balloons. The __init__() method takes the parameters such as the initial position, width, height, and speed of the balloon and loads an image to represent it. The position and the behavior of the balloon are controlled using the “balloonRect” after transforming the “balloon.png” image.

balloon.png

balloon.png

The display() function displays the transformed image on the screen whereas the update() function is used to update the Y coordinate of the balloon. If the balloon goes beyond Y=0, then its position is set back to Y=HEIGHT.

The Arrow Class

This class consists of all the methods needed to control the arrows. The constructor takes in the parameters such as the arrow’s initial position, width, height, and speed. It then loads an image to represent it. The position and behavior of the arrow are controlled using the “arrowRect” after transforming the “arrow.png” image. The image is loaded using the pygame.image.load() method.

arrow.png

The display() function displays the transformed image on the screen whereas the update() function is used to update the arrow’s position. It just increments the arrow’s X coordinate by its speed. The updateHit() function is used to check if the arrow has hit any balloons on its way. If it hits a balloon , then the “hit” variable is set to 1 else it is set to 0. The getHit() function is used to return the value of the “hit” variable maintained by the arrow object. Based on this return value, the decision to reduce a life will be made.

   

The Game Manager

This is used to implement the game logic and control the game objects. The initial score is set to 0 and lives to 5. Then using the pygame.fill() method the background color of the screen is set to “green”. We will use event handling for moving the archer up/down and left/right and also use the space bar for shooting arrows:

  • pygame.K_UP: checks if the “up” key was pressed or not
  • pygame.K_DOWN: checks if the “down” key was pressed or not
  • pygame.K_LEFT: checks if the “left” key was pressed or not
  • pygame.K_RIGHT: checks if the “right” key was pressed or not
  • pygame.K_SPACE: checks if “space-bar” was pressed or not
           

By using the following steps, you will be able to create the Balloon Archer game in Python using the Pygame module.

Complete Implementation of The Balloon Archer Game

            

Python Balloon Archer Game

Python Balloon Archer Game

Working of Python Balloon Archer Game

author

Please Login to comment...

Similar reads.

  • Python Programs
  • Python-PyGame
  • Best 10 IPTV Service Providers in Germany
  • Python 3.13 Releases | Enhanced REPL for Developers
  • IPTV Anbieter in Deutschland - Top IPTV Anbieter Abonnements
  • Best SSL Certificate Providers in 2024 (Free & Paid)
  • Content Improvement League 2024: From Good To A Great Article

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Python Geeks

Learn Python Programming from Scratch

  • Learn Python / Python Projects

Create Snake Game in Python – Snake Game Program using Pygame

Get ready to crack interviews of top MNCs with Placement-ready courses Learn More!

It’s always fun to play games developed by us, let’s develop one of the most popular games – snake game in python. Let’s start making the python project and learn amazing concepts of python.

It’s the most famous game we used to play in our childhood before the advent of smartphones. This is a very simple project in which the snake will eat the food when its mouth touches the food. Furthermore, the length of the snake will keep on increasing after eating the food and if the snake touches the screen or itself the game will be over.

Python Snake Game Project

The objective of this project is to implement the snake game using Python. It requires a specific module pygame to start building the game. You also need to import pygame and random modules. Knowledge of Python functions and loops is required.

Project Prerequisites

This python project requires a good knowledge of the pygame module, concept of functions, loops as they will be used in this snake game project. Basics of the pygame module is a must to start the project.

Download Snake Game Python Code

Please download the source code of python snake game: Snake Game Python Project Code

Project File structure

Steps to follow to built snake game in python:

  • Installing Pygame
  • Importing random and Pygame
  • Creating the game window
  • Displaying score on the screen
  • To make the welcome screen
  • Defining the variables that will be used in the program
  • If the game is over
  • To play the game with the help of arrow keys
  • Eating the food and displaying score
  • Increasing the length of snake
  • If the snake collides with itself or the wall
  • Plotting the snake

Let’s start developing the python snake game

1. Installing Pygame:

Before starting the project you need to install Pygame on your system. It’s a set of modules in Python, which are designed to write code for video games. To install it on your system, write the given command on your command prompt.

2. Importing random and Pygame:

Code Explanation:

  • Import pygame: It is used to import a set of python modules designed to write video games.
  • Import random: It imports the module which generates pseudo-random variables.

3. Creating the snake game window:

We define the variables width_of _screen and height_of_screen to store the width and height of the screen of the game screen

  • pygame.init(): It initializes all the imported modules of pygame for snake game.
  • pygame.display.set_mode(): It helps to set up the screen for display.
  • pygame.display.set_caption(): It displays the caption on the top of your screen.
  • pygame.display.update(): It is used to update the display of the screen.

4. Displaying snake game score on the screen:

This function is defined to display snake game scores on the screen. font.render() takes the text and color of the text and stores it in a variable. blit() function takes this variable and the coordinates of x and y to display it on the screen. This function will be used later in the game to display the score.

5. To make the welcome screen:

This function is defined to display a welcome screen before the start of the snake game.

  • fill(): This function takes the RGB values of color as argument and fills the whole screen with that color.
  • score_on_screen() : This function will display the text on screen.
  • pygame.event.get(): It returns the list of all events that are unprocessed.
  • pygame.QUIT(): It checks whether we are in the game or not.
  • pygame.KEYDOWN(): It checks whether a key is pressed or not.
  • pygame.K_SPACE(): After clicking the space key, the python snake game will start.

6. Defining the variables that will be used in the program:

We define a game function in which various variables are initialized :

  • game_exit: It is initialized to False. Once the variable is True, we will exit from the game.
  • game_over: It is also initialized to False. Once the variable is assigned True the python sanke game will be over.
  • snake_x and snake_y: It is the coordinates of the snake in x and y direction.
  • velocity_x and velocity_y: It is the velocity of the snake in x and y direction which will be changed later in the game.
  • init_velocity: It is the velocity of the snake in the snake game.
  • apple_x and apple_y: It is the position of food in x and y coordinate.
  • snake_size: It is the size of the snake
  • snake_list and snake_length: They will be used further in this function.
  • fps: It is the number of pictures a program can draw in a second.

7. If the snake game is over:

Highscore.txt file is created and high score of python snake game is stored in this file. The file is opened with the use of open() in read mode and the high score is read. If the game is over the high score will be written in that file with the use of f.write().

  • pygame.K_RETURN: After clicking on enter key, the welcome screen will be displayed.

8. To play the snake game with the help of arrow keys:

  • pygame.K_RIGHT: After clicking the right arrow key the velocity in x direction is set to init_velocity and y to 0 so that snake only moves in x direction.
  • pygame.K_LEFT: After clicking the left arrow key the velocity in x direction is set in negative, so that snake moves only in the left direction. Velocity in y direction is set to 0 so that it doesn’t move diagonally.
  • pygame.K_UP: After clicking the up arrow key the velocity is set only in y direction so that the snake only moves in y axis in upward direction.
  • pygame.K_DOWN: After clicking the down arrow key the velocity is set in y direction so that it only moves in y axis in downward direction and not diagonally.

9. Eating the food and displaying score:

  • abs(snake_x-apple_x)<20 and abs(snake_y-apple_y): If the snake comes in this proximity it will eat the food.
  • score_on_screen(): This will display the highest score of python snake game on the screen.

10. Increasing the length of snake:

  • Head: An empty list is initialized and the x,y coordinates are appended in the list.
  • snake_list: Head is appended in this list.

If the length of the snake_list is greater than the length of the snake we will delete the first element of snake_list, so that the length does not increase after every coordinate. It only increases if the snake eats the food.

11. If the snake collides with itself or the wall:

  • Snake_list contains all the coordinates of the snake that it has traveled and the head contains the coordinate of the current position of the snake’s head. If the head of the snake is in the remaining snake_list excluding the first element, it will collide with itself.
  • If the coordinates of the snake in x direction or coordinates in y direction is negative the snake will collide with the wall. Furthermore, if the coordinates of the snake in x direction is greater than the width of the screen or the coordinates of the snake in y direction is greater than the height of the screen in python snake game, the snake will collide with the wall.

12. Plotting the snake:

This function is defined to plot the snake in the snake game.

13. Remaining code:

Python snake game output.

python snake game output

We have successfully developed a snake game in python. We have used pygame to create snake game. We have created various functions to play the game.

Interview questions:

Intermediate level:.

1. What is the output of this code?

This code will display a blank screen of width 900 and height 600. pygame.init() function initializes all the modules that are imported in python. pygame.display.set_mode() takes two arguments: the width and height of the screen.

2. What is the pygame.event.get() function in pygame?

Take the example of this code:

pygame.event.get() stores all the events in an event queue. It is a way to access events of the queue and also pygame interacts with the operating system internally. In this code, if the type of event is QUIT game_exit variable is assigned True. This will help in exiting the game.

Did you know we work 24x7 to provide you best tutorials Please encourage us - write a review on Google | Facebook

Tags: pygame snake game python project python snake game snake game

3 Responses

  • Pingbacks 0

instead of box we using circle??

learning porpose

learning purpose

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

courses

DEV Community

DEV Community

Bala Priya C

Posted on Jul 27, 2023

How To Code a Simple Number Guessing Game in Python

I spent the last weekend compiling a list of games you can code in Python . But why?

If you're a beginner Python programmer, building fun games will help you learn the language faster—and better—without getting bogged down in the syntax and the like. I built some of these games when I was learning Python; I quite enjoyed the process!

The first game you can code—and the simplest of them all—is a number guessing game (or Guess the Number!). So I thought I'd write a step-by-step tutorial to code this game—and help beginners learn some of the fundamentals along the way.

Let's begin!

How Does the Number Guessing Game Work?

In a number guessing game, the user guesses a randomly generated secret number within a given number of attempts.

After each guess, the user gets hints on whether their guess is too high, too low, or correct. So yeah, the game ends when the user guesses the secret number or runs out of attempts.

Coding the Number Guessing Game

Let's get to coding! Create a new Python script and code along.

Step 1 - Import the random module

Let's start by importing the built-in random module. The random module has functions we can use to generate a random secret number within the specified range:

Note : The random module gives pseudo-random numbers—and not truly random numbers. So don't use it for sensitive applications such as password generation.

Step 2 - Set up the range and the maximum number of attempts

Next, we need to decide on the range for the secret number and the maximum number of attempts allowed for the player. For this tutorial, let's set the lower_bound and upper_bound to 1 and 1000, respectively. Also, set the maximum attempts allowed max_attempts to 10:

Step 3 - Generate a random number

Now, let's generate a random number within the specified range using the random.randint() function. This is the secret number that the user needs to guess:

Step 4 - Read in the user's input

To get input from the user, let's create a function called get_guess() . Remember, the user can enter an invalid input: a number outside the range [lower_bound, upper_bound] , a string or a floating point number, and more.

We handle this in the get_guess() function that continuously prompts the user to enter a number—within the specified range—until they provide a valid input.

Here, we use a while loop to prompt the user for a valid input until they enter an integer between lower_bound and upper_bound :

Step 5 - Validate the user's guess

Next, let's define a check_guess() function that takes the user's guess and the secret number as inputs and provides feedback on whether the guess is correct, too high, or too low.

The function compares the player's guess with the secret number and returns a corresponding message:

Step 6 - Track the number of attempts and detect end-of-game conditions

We'll now create the function play_game() that handles the game logic and puts everything together. The function uses the attempts variable to keep track of the number of attempts made by the user. Within a while loop, the user is prompted to enter a guess that's processed by the get_guess() function.

The call to the check_guess() function provides feedback on the user's guess:

  • If the guess is correct, the user wins, and the game ends.
  • Otherwise, the user is given another chance to guess.
  • And this continues until the player guesses the secret number or runs out of attempts.

Here's the play_game() function:

Step 7 - Play the game!

Finally, you can call the play_game() function every time the Python script is run:

Putting it all together

Now our Python script looks like so:

Here's the output from a sample run of the script:

Wrapping Up

Congratulations! You've successfully built a number guessing game in Python. I'll see you all soon in another tutorial. But don't wait for me. Check out other games you can build —features you can code—and start coding!

Top comments (3)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

kingatmo profile image

  • Joined Nov 13, 2018

Hello Bala, Thank you for the article, and the easy-to-follow explanation. It shows that coding in Python can be fun as well. Thanks

balapriya profile image

  • Location India
  • Joined Feb 28, 2021

Thank you for reading, Amos. :)

jarvissilva profile image

  • Joined Mar 28, 2023

here is complete code for Guessing number game in python

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

ceb10n profile image

Understanding FastAPI: How OpenAPI works

Rafael de Oliveira Marques - Jul 24

mikeyoung44 profile image

Comprehensive Guide to Red-Teaming Large Language Models (LLMs) for Robust Security

Mike Young - Jul 24

Pydantic Settings + AWS the easy way

Rafael de Oliveira Marques - Jul 28

vuyokazimkane profile image

Quick Guide: Resolving "Cannot find module 'ajv/dist/compile/codegen'" in React

Vuyokazi Mkane - Jul 24

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Geekflare

How to Create a Tic-Tac-Toe Game in Python?

tic tac toe python

Let us create a simple Tic Tac Toe game in Python. It will help you to build up game logic and understand how to structure code.

Gaming is one of the entertainment that humans have. We can find different types of games on the web, mobile, desktop, etc. We are not here to make one of those heavy games now. We are going to create a CLI tic-tac-toe game using Python .

If you are not familiar with Tic Tac Toe, play it visually here to understand. Don’t worry, even if you don’t understand it, we are going to see it.

Tic Tac Toe

The tutorial is divided into three different sections. In the first section, you will get to know how to play the tic-tac-toe game. After that, we will see an algorithm that helps us to come up with the game logic. Finally, we will see the structured code and its explanation.

You may skip the first section if you already know how to play Tic Tac Toe.

So, without further ado, let’s dive into our first section.

Playing Tic Tac Toe

There will be two players in a game. Two signs represent each player. The general signs used in the game are X  and  O . Finally, there will be a board with 9 boxes.

See the tic-tac-toe board visually.

Tic Tac Toe Board

The gameplay will be as follows.

  • First, one user will place their sign in one of the available empty boxes.
  • Next, the second user will place their sign in one of the available empty boxes.
  • The goal of the players is to place their respective signs completely row-wise or column-wise, or diagonally.
  • The game goes on until a player wins the game or it ended up in a draw by filling all boxes without a winning match.

Let’s see some gameplays visually.

Tic Tac Toe Win Gameplay

The player  X  wins the game in the above gameplay. All boxes diagonally fill with X  signs. So, the respective player wins the game.

There are a total of 8 ways to arrange the same sign and win the game. Let’s see all the 8 arrangements that can win the game.

Tic Tac Toe Winning Arrangements

And finally, a draw fills the board without any winning arrangement. I hope you understand how to Tic Tac Toe now.

Now, it’s playtime for you. You may go here and play it to understand the gameplay completely. Leave it if you have already got it.

Now, it’s time to move the algorithm section.

We will now discuss the algorithm to write the code. This algorithm will help you to write code in any programming language of your choice. Let’s see how it’s done.

  • You can represent empty using any symbol you like. Here, we are going to use a hyphen. '-' .
  • Iterate over the board and return false if the board contains an empty sign or else return true .
  • We have to check all the possibilities that we discussed in the previous section.
  • Check for all the rows, columns, and two diagonals.
  • Write a function to show the board as we will show the board multiple times to the users while they are playing.
  • Select the first turn of the player randomly.
  • Show the board to the user to select the spot for the next move.
  • Ask the user to enter the row and column number.
  • Update the spot with the respective player sign.
  • Check whether the current player won the game or not.
  • If the current player won the game, then print a winning message and break the infinite loop.
  • Next, check whether the board is filled or not.
  • If the board is filled, then print the draw message and break the infinite loop.
  • Finally, show the user the final view of the board.

You may be able to visualize what’s happening. Don’t worry, even if you didn’t understand it completely. You will get more clarity once you see the code.

So, let’s jump into the code section. I assume you have Python installed on your PC to try the code.

Go through the below code.

Check out the sample output of the code.

Some major points that help you understand the structure of the code.

  • We have used a class to have all the methods in one place. It can easily be a reusable bundle in some other code as well.
  • Next, we have defined different functions for each responsibility, even if it is a small task. It helps to maintain the code with ease.
  • The above two approaches help us update the app effortlessly if we want to update the game.

Feel free to adapt the structure and improve it based on your project. Structuring the code is not limited.

Final Words

Hurray! 😎 You have created a game completely from scratch. It is not one of the visual games that we play daily. But it helps you to write logic and maintain clean structure in code. Follow similar guidelines to create some interesting games like this. You can find similar games if you go back some years to your childhood.

Happy Coding! đŸ‘©â€đŸ’»

Next, explore how to create number guessing game and Unit Testing with Python unittest Module .

  • Getting Started
  • Concurrency
  • Unit Testing
  • Other Tutorial
  • ES6 Tutorial
  • Array Methods
  • String Methods
  • Math Functions
  • String Functions
  • Window Functions
  • Date Functions
  • Administration
  • MySQL Index
  • How to Make a Tic Tac Toe Game in Python with Code Example

Building a Tic-Tac-Toe Game in Python: A Step-by-Step Guide

Tic-Tac-Toe, a classic and timeless game, is a perfect starting point for beginners diving into game development with Python. In this step-by-step guide, we will walk through the process of creating a simple yet functional Tic-Tac-Toe game using Python. By the end of this tutorial, you’ll have a fully working game with a graphical user interface.

Table of Contents:

Introduction to Tic-Tac-Toe:

  • Brief overview of Tic-Tac-Toe.
  • Understanding the rules and structure of the game.

Setting Up Your Development Environment:

  • Choosing a code editor (e.g., VSCode, PyCharm).
  • Installing Python if not already installed.

Planning the Game Structure:

  • Identifying key components: the game board, players, and turns.
  • Deciding on data structures for the game board representation.

Creating the Game Board:

  • Defining the Tic-Tac-Toe grid.
  • Displaying the initial game board.

Player Input and Turns:

  • Obtaining player input for moves.
  • Alternating turns between two players.

Validating Moves:

  • Ensuring the selected cell is empty.
  • Handling invalid moves.

Updating the Game Board:

  • Modifying the board based on valid moves.
  • Checking for a win or a tie after each move.

Checking for a Winner:

  • Implementing the logic to determine if a player has won.
  • Recognizing horizontal, vertical, and diagonal wins.

Handling a Tie:

  • Determining when the game ends in a tie.
  • Displaying the final result.

Putting It All Together:

  • Integrating the components into a cohesive Tic-Tac-Toe game.
  • Running the game loop until a winner or a tie is determined.
  • Adding more features such as a graphical interface.
  • Exploring advanced topics like artificial intelligence opponents.

By following these steps, you’ll have successfully created a basic yet functional Tic-Tac-Toe game in Python. Feel free to experiment, enhance, and explore more advanced concepts as you continue your journey into Python game development. Happy coding!

  • by python-tutorials.in
  • on 26th January 2024

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

Recent Posts

  • Palindrome Program in C Using Functions and Pointers
  • Palindrome in C without Using String Functions: A Comprehensive Guide
  • Palindrome Program in Python
  • How to install PIP on Windows
  • 15 Python Projects for Beginners with Source Code
  • C programming
  • Java Examples
  • Java programs
  • JavaScript Program Examples
  • JavaScript Tutorial
  • Kotlin Examples
  • Machine Learning with Python
  • MySQL Tutorial
  • New program
  • New Python tutorial
  • PHP Tutorial
  • python basic
  • Python basic tutorials
  • Python Database Tutorials
  • Python note
  • Python Programming Examples
  • Python Programming Practice
  • Python Programs
  • Python Programs Tutorials
  • Python Tkinter Tutorial
  • Python Tutorials
  • SQLite Tutorial

©  2024 python tutorials.  python-tutorials.in

Python Programming

Practice Python Exercises and Challenges with Solutions

Free Coding Exercises for Python Developers. Exercises cover Python Basics , Data structure , to Data analytics . As of now, this page contains 18 Exercises.

What included in these Python Exercises?

Each exercise contains specific Python topic questions you need to practice and solve. These free exercises are nothing but Python assignments for the practice where you need to solve different programs and challenges.

  • All exercises are tested on Python 3.
  • Each exercise has 10-20 Questions.
  • The solution is provided for every question.
  • Practice each Exercise in Online Code Editor

These Python programming exercises are suitable for all Python developers. If you are a beginner, you will have a better understanding of Python after solving these exercises. Below is the list of exercises.

Select the exercise you want to solve .

Basic Exercise for Beginners

Practice and Quickly learn Python’s necessary skills by solving simple questions and problems.

Topics : Variables, Operators, Loops, String, Numbers, List

Python Input and Output Exercise

Solve input and output operations in Python. Also, we practice file handling.

Topics : print() and input() , File I/O

Python Loop Exercise

This Python loop exercise aims to help developers to practice branching and Looping techniques in Python.

Topics : If-else statements, loop, and while loop.

Python Functions Exercise

Practice how to create a function, nested functions, and use the function arguments effectively in Python by solving different questions.

Topics : Functions arguments, built-in functions.

Python String Exercise

Solve Python String exercise to learn and practice String operations and manipulations.

Python Data Structure Exercise

Practice widely used Python types such as List, Set, Dictionary, and Tuple operations in Python

Python List Exercise

This Python list exercise aims to help Python developers to learn and practice list operations.

Python Dictionary Exercise

This Python dictionary exercise aims to help Python developers to learn and practice dictionary operations.

Python Set Exercise

This exercise aims to help Python developers to learn and practice set operations.

Python Tuple Exercise

This exercise aims to help Python developers to learn and practice tuple operations.

Python Date and Time Exercise

This exercise aims to help Python developers to learn and practice DateTime and timestamp questions and problems.

Topics : Date, time, DateTime, Calendar.

Python OOP Exercise

This Python Object-oriented programming (OOP) exercise aims to help Python developers to learn and practice OOP concepts.

Topics : Object, Classes, Inheritance

Python JSON Exercise

Practice and Learn JSON creation, manipulation, Encoding, Decoding, and parsing using Python

Python NumPy Exercise

Practice NumPy questions such as Array manipulations, numeric ranges, Slicing, indexing, Searching, Sorting, and splitting, and more.

Python Pandas Exercise

Practice Data Analysis using Python Pandas. Practice Data-frame, Data selection, group-by, Series, sorting, searching, and statistics.

Python Matplotlib Exercise

Practice Data visualization using Python Matplotlib. Line plot, Style properties, multi-line plot, scatter plot, bar chart, histogram, Pie chart, Subplot, stack plot.

Random Data Generation Exercise

Practice and Learn the various techniques to generate random data in Python.

Topics : random module, secrets module, UUID module

Python Database Exercise

Practice Python database programming skills by solving the questions step by step.

Use any of the MySQL, PostgreSQL, SQLite to solve the exercise

Exercises for Intermediate developers

The following practice questions are for intermediate Python developers.

If you have not solved the above exercises, please complete them to understand and practice each topic in detail. After that, you can solve the below questions quickly.

Exercise 1: Reverse each word of a string

Expected Output

  • Use the split() method to split a string into a list of words.
  • Reverse each word from a list
  • finally, use the join() function to convert a list into a string

Steps to solve this question :

  • Split the given string into a list of words using the split() method
  • Use a list comprehension to create a new list by reversing each word from a list.
  • Use the join() function to convert the new list into a string
  • Display the resultant string

Exercise 2: Read text file into a variable and replace all newlines with space

Given : Assume you have a following text file (sample.txt).

Expected Output :

  • First, read a text file.
  • Next, use string replace() function to replace all newlines ( \n ) with space ( ' ' ).

Steps to solve this question : -

  • First, open the file in a read mode
  • Next, read all content from a file using the read() function and assign it to a variable.
  • Display final string

Exercise 3: Remove items from a list while iterating

Description :

In this question, You need to remove items from a list while iterating but without creating a different copy of a list.

Remove numbers greater than 50

Expected Output : -

  • Get the list's size
  • Iterate list using while loop
  • Check if the number is greater than 50
  • If yes, delete the item using a del keyword
  • Reduce the list size

Solution 1: Using while loop

Solution 2: Using for loop and range()

Exercise 4: Reverse Dictionary mapping

Exercise 5: display all duplicate items from a list.

  • Use the counter() method of the collection module.
  • Create a dictionary that will maintain the count of each item of a list. Next, Fetch all keys whose value is greater than 2

Solution 1 : - Using collections.Counter()

Solution 2 : -

Exercise 6: Filter dictionary to contain keys present in the given list

Exercise 7: print the following number pattern.

Refer to Print patterns in Python to solve this question.

  • Use two for loops
  • The outer loop is reverse for loop from 5 to 0
  • Increment value of x by 1 in each iteration of an outer loop
  • The inner loop will iterate from 0 to the value of i of the outer loop
  • Print value of x in each iteration of an inner loop
  • Print newline at the end of each outer loop

Exercise 8: Create an inner function

Question description : -

  • Create an outer function that will accept two strings, x and y . ( x= 'Emma' and y = 'Kelly' .
  • Create an inner function inside an outer function that will concatenate x and y.
  • At last, an outer function will join the word 'developer' to it.

Exercise 9: Modify the element of a nested list inside the following list

Change the element 35 to 3500

Exercise 10: Access the nested key increment from the following dictionary

Under Exercises: -

Python Object-Oriented Programming (OOP) Exercise: Classes and Objects Exercises

Updated on:  December 8, 2021 | 52 Comments

Python Date and Time Exercise with Solutions

Updated on:  December 8, 2021 | 10 Comments

Python Dictionary Exercise with Solutions

Updated on:  May 6, 2023 | 56 Comments

Python Tuple Exercise with Solutions

Updated on:  December 8, 2021 | 96 Comments

Python Set Exercise with Solutions

Updated on:  October 20, 2022 | 27 Comments

Python if else, for loop, and range() Exercises with Solutions

Updated on:  August 29, 2024 | 298 Comments

Updated on:  August 2, 2022 | 155 Comments

Updated on:  September 6, 2021 | 109 Comments

Python List Exercise with Solutions

Updated on:  December 8, 2021 | 201 Comments

Updated on:  December 8, 2021 | 7 Comments

Python Data Structure Exercise for Beginners

Updated on:  December 8, 2021 | 116 Comments

Python String Exercise with Solutions

Updated on:  October 6, 2021 | 221 Comments

Updated on:  March 9, 2021 | 23 Comments

Updated on:  March 9, 2021 | 51 Comments

Updated on:  July 20, 2021 | 29 Comments

Python Basic Exercise for Beginners

Updated on:  August 29, 2024 | 498 Comments

Useful Python Tips and Tricks Every Programmer Should Know

Updated on:  May 17, 2021 | 23 Comments

Python random Data generation Exercise

Updated on:  December 8, 2021 | 13 Comments

Python Database Programming Exercise

Updated on:  March 9, 2021 | 17 Comments

  • Online Python Code Editor

Updated on:  June 1, 2022 |

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills .

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Python Tricks

To get New Python Tutorials, Exercises, and Quizzes

Legal Stuff

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use , Cookie Policy , and Privacy Policy .

Copyright © 2018–2024 pynative.com

allinpython.com

Create a simple quiz game program in python with score

In this post, you will learn how to create a simple quiz game program in python with a proper explanation and algorithm.

game assignment in python

this python program is considered as a mini-project for beginners and also helps them to boost their knowledge and confidence (this project gives you the confidence to learn more and more things) but before writing the program let’s understand the algorithm for a python quiz game.

Algorithm for a Simple python quiz game

  • Create one variable for counting score e.g score .
  • Ask questions to a user (using the input() function)
  • if a user gives a correct answer then increase a score by 1 and print(correct!)
  • if given answer of a user is incorrect then print(incorrect !)
  • and at last print score of the user.

Now you understand how to implement a simple quiz game in python through an above algorithm.

Few programming concepts you have to know for writing this program such as

  • nested if-else
  • how to take user input in python .

Source code

question ask like: write a python program to create a quiz game.

Hope this post adds some value to your life – thank you.

Another projects:

Hangman game

Simple calculator

Number guessing game

' src=

Hi, I'm Yagyavendra Tiwari, a computer engineer with a strong passion for programming. I'm excited to share my programming knowledge with everyone here and help educate others in this field.

Related Posts

How to Convert Text to Speech in Python

How to Convert Text to Speech in Python

Password Generator in Python with User Input

Password Generator in Python with User Input

How to Convert JPG to PNG in Python

How to Convert JPG to PNG in Python

Calculate Age from Date of Birth in Python

Calculate Age from Date of Birth in Python

Remove Background From Images in Python

Remove Background From Images in Python

Calculate Electricity Bill in Python

Calculate Electricity Bill in Python

Write a comment cancel reply.

Save my name, email, and website in this browser for the next time I comment.

Type above and press Enter to search. Press Esc to cancel.

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectivesℱ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Python - Guess Who game - Im not getting my expected output

This is a small portion of my guess who game im developing that assigns the AI Opponents randomly chosen character with its linked features, and assigns those features to the feature variables. When the user asks the question the if statements will respond with a yes or no based on whether it has the features asked off, but i am not getting an expected output. I may not be able to reply with any further questions about this until i get back from college later today thanks.

I do not get any errors, but every response is a "No" even when the AI opponent 100% definetely has that feature. Heres the output im getting:

What is your question for your AI opponent? Does your character have short hair? AI Opponent: No What is your question for your AI opponent? Does your character have long hair? AI Opponent: No What is your question for your AI opponent? Is your character Bald? AI Opponent: No What is your question for your AI opponent? Is your character male? AI Opponent: No What is your question for your AI opponent? Is your character female? AI Opponent: No

ComputerExpert69's user avatar

2 Answers 2

You're not assigning inside the conditional name check bit:

Also - I would seriously think about reading up a bit on Object-Oriented Programming. If you make your characters an object, with some associated methods - it will save you a lot of typing. I'll try and put together something for you this morning to demonstrate.

EDIT - as promised. I got a bit carried away learning about NLTK , so for my code to work, you'll have to make sure you've got NLTK on your python distribution (you will also need numpy if you don't already have it):

  • Navigate to your Scripts folder (i.e. C:\Python27\Scripts ) in a command prompt (NB: assuming that you're using Windows and Python 2.7 - if not, tell me and I'll adjust answer)
  • Then type pip install nltk

I've also used a simple statistical language parser pyStatParser . To add this to python:

  • Download the package from github
  • Unzip into your Lib folder of python (i.e. C:\Python27\Lib ) - this is just good practice
  • Navigate to folder in cmd and run the file named Setup.py by typing python Setup.py install

This should be all the setup you need to get the code working. Installing and playing with these packages will make your game more interesting and challenging for you to develop (in my opinion). It should also make for a more 'updatable' game.

Here is my code. It sets up your Character as a class , which you can then make instances of (an object ). Classes allow you to grow your code over time - whilst having minimal impact on the code already functioning correctly:

The class Character has two associated methods (special name for functions inside classes):

  • __init__ - this is a special python function that initialises your object. It takes a number of arguments, the first once being self . It can then manipulate these parameters. In my version - I set up a number of internal variables.
  • answer - this is called in the function ask_question (which takes your question text and a Character instance as arguments). When you call this function, you access it as a member function of the created object Dave by typing character.answer(arg1, arg2) . This automatically passes self (in this example; character ) into the function. answer interrogates the variables set up in __init__ and should return the answers to your questions.

The code works on the test cases you included in your answer. As parsing natural language is complicated, you might have to tweek it to accept different forms of answers.

Let me know if you have any questions / problems. I hope this helps. I've certainly learnt some things in answering your question anyway.

Aidenhjj's user avatar

  • Ok thanks for the fix i will change that now, also i will have a look at object-oriented programming as you suggested if you think it will save me from typing huge amounts of code. –  ComputerExpert69 Commented Oct 14, 2016 at 15:23
  • Well thank you very much for that, i will get right onto installing those in my python library straight after my dinner! ;) –  ComputerExpert69 Commented Oct 14, 2016 at 17:15
  • I've just realised from your original code submission that you're working in python3. I was just trying to run the code in python3, but that pyStatParser was written in python27. I'm not clever enough to get around it. I tried installing future and using the following directions ( python-future.org/translation.html ), but I couldn't get it to take. Maybe you'll have more joy. –  Aidenhjj Commented Oct 14, 2016 at 17:20
  • So, you could either switch to python27 for this project, or find some other way of parsing natural language. –  Aidenhjj Commented Oct 14, 2016 at 17:21

AIChoiceFeatureHairLength == "Short" is a conditional statement, it will evaluate to either True or False .

What you want to do is a assignement like this: AIChoiceFeatureHairLength = "Short"

I would also recommend using dictionaries like:

You can put the dictionaries in a list ( [Greg, Chris, etc] ) and use the random.choice() function on that.

You can acces an entry in a dictionary with Greg["HairLenght"] and it will return "Short" .

This will shorten the code a lot and you also don't need to introduce the variables as ="unassigned"

Linda's user avatar

  • First of all, thanks! Second of all, yes i have used a dictionary and the random.choice function to choose a random character for the opponent. Also i think i will try and make each character its own dictionary as that will save some typing, as you mentioned. –  ComputerExpert69 Commented Oct 14, 2016 at 15:19

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged python output or ask your own question .

  • The Overflow Blog
  • Where does Postgres fit in a world of GenAI and vector databases?
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • Reusing own code at work without losing licence
  • How much missing data is too much (part 2)? statistical power, effective sample size
  • Has the US said why electing judges is bad in Mexico but good in the US?
  • Topology on a module over a topological ring
  • Briefly stopped at US Border because I read books
  • Why did General Leslie Groves evade Robert Oppenheimer's question here?
  • How would increasing atomic bond strength affect nuclear physics?
  • Does the Greek used in 1 Peter 3:7 properly translate as “weaker” and in what way might that be applied?
  • Story where character has "boomerdisc"
  • Is it possible to have a planet that's gaslike in some areas and rocky in others?
  • How do I make a command that makes a comma-separated list where all the items are bold?
  • A very interesting food chain
  • Stuck on Sokoban
  • How can I get an Edge's Bevel Weight attribute value via Python?
  • How to reply to reviewers who ask for more work by responding that the paper is complete as it stands?
  • Completely introduce your friends
  • Are quantum states like the W, Bell, GHZ, and Dicke state actually used in quantum computing research?
  • Can a subgroup be covered by a non-conjugate subgroup?
  • Do metal objects attract lightning?
  • about flag changes in 16-bit calculations on the MC6800
  • Meaning of "blunk"
  • Who was the "Dutch author", "Bumstone Bumstone"?
  • Which programming language/environment pioneered row-major array order?
  • Should I report a review I suspect to be AI-generated?

game assignment in python

Defining a symbolic syntax for referring to assignment targets

FWIW, aside from the potential performance hit, mutating f_locals should work reliably in 3.13+ due to PEP 667 – Consistent views of namespaces | peps.python.org

I actually had thought about that too but the problem was that we can’t use a soft keyword for it since there is no way syntactically to distinguish the soft keyword from a variable name, and if we make it a hard keyword then it would be too much of a breaking change since the keyword would have to be a commonly used English word that likely collides with variable names in existing code base.

But now it occurred to me that we can just make the magic placeholder a dunder so no existing code base should be using it. As for the name itself, I think __target__ would be good:

The code now looks a lot less cryptic/Perlish to me.

Behind the scene though, __target__ would be a hard keyword rather than a variable name. It won’t be looked up in the namespace but is rather expanded at compilation time.

Similarlly, @'' can be made into a new hard keyword such as __target_name__ to look less cryptic.

Yup, same here. I almost wrote my own POV comparing this to walrus, but decided not to half-way through realising that it isn’t going to be of much use given this is currently at contemplative stage.

And it took me a fair bit of time to stop abusing walrus, however I am happy about it having finally learned to use it responsibly.

The notation, I think is decent - visually and semantically. And been wandering what was the reason for @ for mat_mult - never seen @ used anywhere in math before. There was quite a good example for this - matlab . Can’t do exactly the same, but retaining * might have been better, e.g. \* . So that @ could be used for something more appropriate, e.g. this. But given status quo, I don’t think it would fly. So 2 options:

  • Change matrix multiplication operator. Been thinking about how hard of a sell this would be. I know that no-one would want to do it. All the backwards compatibility etc, but has anyone analysed compound cost of a bad decision? And the fact that the earlier the correction is done, the smaller the damage? I am talking in general, not only this specific case. I mean surely if the goal is best possible version of Python, (as opposed to pleasing unsatisfied and reluctant to adapt users), big breaks of backwards compatibility are inevitable

  • Pick something else for this. One idea would be to go with bash-like argument syntax, but with pythonic slicing:

Or maybe even star, given it being used in expansions:

Could also incorporate string-like formatting:

Alternatively, use * for strings, @ for values (similar to what bash does).

We have space-separated names as arguments in the standard library too, such as collections.namedtuple and enum.Enum :

Using my dunder keyword idea above, it can become:

The matrix multiplication PEP did cover that: PEP 465 – A dedicated infix operator for matrix multiplication | peps.python.org

The __target__ dunder idea is interesting, as it doesn’t provide brevity gains in most cases, but does provide the benefit of avoiding repeated evaluation.

I suspect code that assigns to identifiers would continue to be better off just using the target identifier directly, but attribute access, subscripting, slicing, and tuple assignment could still see some utility.

__target_text__ could replace @'' for both identifier assignment and tuple assignment ( __target_name__ wouldn’t match the latter use case)

I doubt you could reasonably use that form to map function parameters to local variables of the same name, though.

Sounds good indeed. With the name __target_text__ we wouldn’t have to worry about a plural form.

I don’t see why not. We can name the new keyword that forwards local variables to function parameters of the same names, __same__ . The compiler with access to AST can clearly tell which keyword argument a ast.Same node belongs to and produces bytecode that loads the local variable of that name for the argument accordingly:

This is really a completely separate proposal from the assignment target placeholder proposal though, and should be discussed about in a separate thread (perhaps in the PEP-736 thread, in which I have now made a post ).

Yeah the loss of brevity does take away the utility of this idea in cases of a single identifier, particularly as an alternative to PEP-736, where parameter names are always single identifiers.

I agree that we should focus more on its utility for more complex assignment targets.

Going further on the SymPy tangent, I can brainstorm a possible story of how to get that by more straightforward extensions of existing syntax.

The hardest hurdle in this story is the first step. Suppose Python somehow gets dict destructuring assignment:

Sympy then defines a helper whose __getitem__ gives out symbols (if it doesn’t already have it):

By this time PEP 736 has been accepted, and its syntax gets extended to dict destructuring:

(Is that Perlish?) (Is it the direction Python is going?)

People now start writing {Point2D=} = namedtuplemaker('x', 'y') 
 which isn’t straightforward to read today, but maybe it’s better than with @'' ?

“Whatever, we have to pick something.”

If you’re going to give the target a full identifier, you might as well provide the name rather than hardcoding it

some.nested.attribute as x = x.lower()

This doesn’t require new tokens, and the syntax mimics what we have in the match statement (which tries to overlap assignment syntax). It definitely looks more python than perl (keywords vs symbols)

Same as your proposal, this doesn’t cover argument pushing, but only double evaluation (at this point it isn’t much more than a glorified walrus). This is also missing a syntax to capture the name of the target as a str. I’m not sorry convinced on that but I think you could do (a, b, c) as (_, names) = simpy.symbols(names) .

I’m not super sold into this either, but hopefully putting this idea on the table may help someone find a better proposal

For me a big part of this feature was not needing to assign a name for this specific “some.nested.attribute”, so I’m not really sure I like the as proposal

A benefit can be that if the name persists, it can be used more times in the code that follows the assignment.

Quite like it, one issue though:

While naming tuple thing obstruct such intuitive expansion. However might not be an issue as one can always slice it on the right hand side. However, it does not seem very elegant nevertheless. Maybe something like:

This would be the 2nd method that allows extracting identifier name from identifier. First one being f{a=} . However, it would also be the second one which compulsory does more than that, while simple straight forward way to do this still does not exist, namely something similar to C# nameof , that would do exactly that without needing to evaluate anything. Thinking if I could hack this for it:

Interesting idea, for sure.

What I don’t like about it is that it encourages a coding style that binds multiple different values to the same name. Inevitably, one of those values is going to be badly named.

E.g. you might see

At point (1) , the value of sth.this_must_be_lowercase violates requirements: The value is in fact not guaranteed lowercase.

I would rather it was written such that different values have different names. Like this:

This is a fairly marginal coding style distinction, and not something I would usually make a fuss about. But I do think the latter style is marginally better, and it would be unfortunate to add syntax that encourages the former style.

I am -1 to using @ for any of the purposes outlined here, but +1 to long_name as x = foo(x) being sugar for long_name = foo('long_name') .

It should work the same for dotted names and tuples, i.e. a.b. c as x = foo(x) would be sugar for a.b. c = foo('a.b.c') and (a,*b, c) as x = foo(x) would be sugar for (a,*b, c) = foo('a, *b, c') - note my intentional inconsistent whitespace to demonstrate that whitespace ought to be normalised when generating the string representation.

Outer parens in tuple assignment would be required to make it clearly unambiguous; a, b as x would be a syntax error but might later (as a separate proposal) be allowed in order to let x be 'b' . I’m -0 on allowing this from the beginning; probably better to see how the general idea works out before adding in this complication.

I would prefer that this feature be limited to passing the string representation of some name to a function (or otherwise using it in an expression), as that’s an actually important use case (namedtuple, TypeVar). My dislike of using this for accessing the target object itself is pretty much what @AndersMunch has already explained: it’s far less confusing to just use a regular ol’ assignment for that.

“Python is not Perl” indeed!

IMO another good (also English-specific) mnemonic is “at rhymes with that”, and reading @ as “that” is a pretty natural way to speak the statement.

I suspect that I’m in the minority here but I personally found figuring out what assignment target means (i.e. whatever’s on the the left of the = operator) to be more confusing than mapping a punctuation character to the words assignment target . So perlish or not, to me eliminating @ isn’t really fixing anything.

TBH, in this version of the proposal you don’t get much for TypeVar . You are changing:

if you make up a name and copy it over you’re getting more verbosity than the original and still have repetition. Same for namedtuples. That’s whay I didn’t worry too much about the string representation when I covered this, I was more focused on Alyssa’s idea of avoiding re-evaluation of attribute accesses/slicing.

We have __set_name__ so descriptors know their own name. Have we thought of extending __set_name__ to work on objects? Or perhaps there is a reason why it’s not done? I think it would be neat if objects could capture the lhs as a name like in descriptors

(post deleted by author)

Allowing __target__ on the LFS would make the syntax ambiguous when there is also __target__ on the RHS:

Does __target__[:2] on the RHS become foo[:2] or foo[2:][:2] ?

Assignment to a name does not modify an object in-place. It merely sets the name on the LHS to a new reference to the object on the RHS. So __target__ = hex(v) would just set the local name v to a new object for that iteration rather than updating the entry in mydict , which will still hold a reference to the original value.

As Twins’ free fall continues, Byron Buxton still needs to up intensity before rehab game

MINNEAPOLIS, MN - AUGUST 11: Byron Buxton #25 of the Minnesota Twins warms up before the game against the Cleveland Guardians at Target Field on August 11, 2024 in Minneapolis, Minnesota. (Photo by Adam Bettcher/Getty Images)

MINNEAPOLIS — All that’s left for Byron Buxton is to take it up a notch.

The injured Minnesota Twins center fielder is closing in on the start of a rehab assignment, though he has a few more steps to take. Out since Aug. 15 with right hip inflammation, Buxton reported feeling good after a full day of work Wednesday afternoon.

Advertisement

Twins manager Rocco Baldelli suggested Buxton, who’s batting .275/.334/.528 with 16 home runs and 49 RBIs in 90 games, would first need to appear in a minor-league rehab game before rejoining the club.

Buxton’s nearing that milestone but isn’t quite ready.

“I’ve been out here and been going through the stuff, but the intensity for me is not there,” Buxton said. “You just have to find that intensity to push it but not overdo it. That’s where the one day at a time comes in. There’s days where I feel good and I can go out there and can overdo it. They’re doing a good job keeping me within myself and understanding that we’ve still got a month left. We all know the situation: Want to be back, want to be back playing.”

As the Twins continued their free fall with a 5-1 loss to the Atlanta Braves on Wednesday, the team’s eighth defeat in 10 games, the intensity provided by Buxton and shortstop Carlos Correa is missed. Correa has been out of the lineup since July 12 as he continues to recover from plantar fasciitis in his right heel.

Willi steps up with two outs and we're tied! #MNTwins #MLB pic.twitter.com/opgNsmdRMc — Bally Sports North (@BallySportsNOR) August 29, 2024

One Twins source Wednesday described Buxton as much closer to rejoining the big-league club than the All-Star Correa, who is making only incremental progress. Still, Buxton might not begin a rehab assignment until early next week.

Buxton dealt with a hip strain in 2021, missing six weeks. After Buxton’s MRI showed no structural damage earlier this month, Twins athletic trainer Nick Paparesta opined the inflammation is likely due to scar tissue from the previous injury that resurfaced.

Buxton noticed his hip soreness while in the field in an Aug. 12 contest and felt it again when he batted to start the next inning. He removed himself from the game shortly thereafter. Early in the recovery process, Buxton was often forced to lie down because he felt discomfort even when doing something simple like sitting.

Though sprinting and slowing down are still issues, Buxton feels like he’s making good progress.

“There’s a lot of things I do and it feels good,” Buxton said. “Still feel strong, so that’s the best thing. But there’s still a few things that’s getting over the hump and getting over that curve a little, to not put us in a worse position when I do come back. I wouldn’t want to come back and play a couple days and it reoccurs because I didn’t take the extra couple of days on the front end to get it right. Not being cautious, but there’s still a little in there. But it definitely feels better and feels close.”

Earlier in the week, Baldelli suggested Buxton would likely need only a quick rehab assignment whenever it begins.

Disaster strikes again as Twins fall to Braves

Atlanta completed a sweep of Minnesota on Wednesday night.

In doing so, the Twins completed a trifecta of their own in a brief window, hitting on all of their fans’ most popular gripes: base-running mistakes, a bad bullpen and Manny Margot.

Trailing by a run in the sixth inning with no outs, third-base coach Tommy Watkins made an ill-advised decision to send Margot home on a Ryan Jeffers single off Chris Sale . After doubling to start the inning, Margot appeared to at first break back to the bag on Jeffers’ single before briefly slowing as he reached third base. Watkins sent him anyway against the powerful, accurate arm of Atlanta right fielder Jorge Soler , who made an on-target throw to easily cut down Margot for the first out.

Though the Twins tied the score later in the inning, their joy was short-lived.

Starter David Festa ended the best outing of his young career by walking Marcell Ozuna to start the seventh inning, which ended his night. Reliever Caleb Thielbar took over, and lefty Matt Olson smoked a low 1-2 sweeper into the gap for a go-ahead RBI double. RamĂłn Laureano followed by singling in a run to make it a 3-1 game.

Jorge Alcala entered and looked like he’d keep the score in place. Then No. 9 hitter Luke Williams hit a long, tailing drive to left that Margot misread. As he retreated toward the fence, the ball tailed back to his left and bounced off Margot’s glove, going for a two-run double to put away the game.

Bases cleared! 💹 #BravesCountry pic.twitter.com/LgNOmRj5U0 — Atlanta Braves (@Braves) August 29, 2024

“We’ve hit a bump,” Baldelli said. “I really don’t want to watch these kinds of games anymore — no one does. It’s time to shake ourselves and start one of those streaks after the streak, which we’ve done a lot of.”

The team’s latest disaster spell wiped out what had been a rather entertaining game.

Though Sale silenced them for five innings, the Twins scratched and clawed, driving up the All-Star’s pitch count. The Twins loaded the bases in the fourth inning before Sale overpowered them to escape the jam.

But Festa was equally effective, leaning heavily on his slider to keep the Braves off the board. Aside from Soler’s first-inning solo homer, Festa was outstanding. He retired 17 of 18 batters after the homer and struck out seven, including five in a row.

Festa returned to start the seventh inning but couldn’t put away Ozuna after getting ahead 1-2 in the count, walking him and giving way to Thielbar.

“I probably won’t sleep much tonight, honestly,” Festa said. “I was confident that I was going to put (Ozuna) away with the slider or the changeup, and I just didn’t execute. 
 I’m pretty hard on myself. Just can’t afford to put the leadoff guy on in a 1-1 game in the seventh.”

Overall, Festa was happy with the outing, in which he allowed two earned runs and two hits in six-plus innings. His manager was ecstatic.

“If he’s throwing the ball like that, we’re going to want to give him opportunities to face another hitter or grab another inning,” Baldelli said. “(When a young pitcher) gets to the big leagues, this is what you want it to look like.”

(Photo: Adam Bettcher / Getty Images)

Get all-access to exclusive stories.

Subscribe to The Athletic for in-depth coverage of your favorite players, teams, leagues and clubs. Try a week on us.

Dan Hayes

Dan Hayes is a senior writer for The Athletic covering the Minnesota Twins. Dan joined The Athletic after 5 1/2 years at NBC Sports Chicago and eight years at The North County Times, where he covered the Chicago White Sox, San Diego Padres, four World Series, the NBA Finals, NHL Stanley Cup Final, NASCAR, UFC, Little League World Series, PGA and the NFL. Follow Dan on Twitter @ DanHayesMLB

  • SI SWIMSUIT
  • SI SPORTSBOOK

Astros Designate Former Dodgers Prospect For Assignment

Maren angus-coombs | aug 26, 2024.

game assignment in python

  • Los Angeles Dodgers

The Astros announced several roster changes on Sunday, including designating infielder Jacob Amaya for assignment.

Amaya, once a Los Angeles Dodgers prospect, joined the Astros in a trade with the Marlins this April. However, he only saw action in one game for Houston, entering as a defensive substitute during their 10-3 loss to the Yankees on May 7.

The 25-year-old posted a .221/.308/.330 slash line across 302 plate appearances this season, split between the Triple-A affiliates of the Astros and Marlins.

Astros moves today: -- Hector Neris signed -- Seth Martinez, Shawn Dubin optioned to Triple-A -- Kaleb Ort reinstated from paternity list -- Jacob Amaya DFA'd — Brian McTaggart (@brianmctaggart) August 24, 2024

Amaya’s season has been eventful, to say the least. He began with the Marlins’ Triple-A Jacksonville affiliate, but after just three games, Miami designated him for assignment. This left him in a state of uncertainty, spending a week in a Durham, N.C., hotel, waiting for his next move.

On April 6, Amaya received a call from Marlins general manager Peter Bendix, informing him that he had been traded to the Houston Astros in exchange for minor league pitcher Valente Bellozo and cash.

Amaya spent the majority of 2023 playing for Triple-A Jacksonville, batting .252 with 26 doubles, two triples, 15 home runs, 65 RBI, and a .752 OPS in 128 games.

"It was a relief, just to hear something," Amaya shared on May 2 . "But coming to a winning organization, that’s everything. So I just stayed ready."

Amaya was called up to the Astros on May 1, following an injury to Chas McCormick, who was placed on the 10-day injured list with a hamstring issue. At that time, reserve infielder Grae Kessinger was also on the 10-day IL with right shoulder discomfort.

Amaya provided the Astros with much-needed depth at second base, shortstop, and third base, as Jose Altuve, Jeremy Peña, and Alex Bregman had played nearly every game of the season. Manager Joe Espada told the Houston Chronicle on May 2 that he needed to give his regulars a day off, and Amaya fit the role perfectly as a versatile fill-in.

Originally an 11th-round pick by the Dodgers in the 2017 draft, Amaya spent his first five professional seasons with Los Angeles before being traded to Miami ahead of the 2023 season in exchange for Miguel Rojas. Known for his defensive skills, Amaya made his major league debut with the Marlins in 2023, appearing in four games.

This is Amaya's first time being designated for assignment, so if he clears waivers and is outrighted to Triple-A, he cannot reject the assignment in favor of free agency due to his lack of prior outright experience and MLB service time.

Maren Angus-Coombs

MAREN ANGUS-COOMBS

Maren Angus-Coombs was born in Los Angeles and raised in Nashville, Tenn. She is a graduate of Middle Tennessee State and has been a sports writer since 2008. Despite growing up in the South, her sports obsession has always been in Los Angeles. She is currently a staff writer at the LA Sports Report Network.

Build a Tic-Tac-Toe Game Engine With an AI Player in Python

Build a Tic-Tac-Toe Game Engine With an AI Player in Python

Table of Contents

Demo: Tic-Tac-Toe AI Player in Python

Project overview, prerequisites, enumerate the players’ marks, represent the square grid of cells, take a snapshot of the player’s move, determine the game state, introduce a separate validation layer, discard incorrect game states, simulate moves by producing new game states, pull the players’ moves to drive the game, let the computer pick a random move, make an abstract tic-tac-toe grid renderer, render the grid with ansi escape codes, create an interactive console player, add a command-line interface (cli), evaluate the score of a finished game, propagate the score with the minimax algorithm, make an undefeatable minimax computer player.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Create a Tic-Tac-Toe Python Game Engine With an AI Player

When you’re a child, you learn to play tic-tac-toe , which some people know as naughts and crosses. The game remains fun and challenging until you enter your teenage years. Then, you learn to program and discover the joy of coding a virtual version of this two-player game. As an adult, you may still appreciate the simplicity of the game by using Python to create an opponent with artificial intelligence (AI) .

By completing this detailed step-by-step adventure, you’ll build an extensible game engine with an unbeatable computer player that uses the minimax algorithm to play tic-tac-toe. Along the way, you’ll dive into immutable class design, generic plug-in architecture, and modern Python code practices and patterns.

In this tutorial, you’ll learn how to:

  • Create a reusable Python library with the tic-tac-toe game engine
  • Model the domain of tic-tac-toe following Pythonic code style
  • Implement artificial players including one based on the minimax algorithm
  • Build a text-based console front end for the game with a human player
  • Explore strategies for performance optimizations

Click the link below to download the complete source code for this project:

Source Code: Click here to download the free source code that you’ll use to build a tic-tac-toe game engine and AI player with Python.

By the end of this tutorial, you’ll have a highly reusable and extensible Python library with an abstract game engine for tic-tac-toe. It’ll encapsulate universal game rules and computer players, including one that never loses due to bare-bones artificial intelligence support. In addition, you’ll create a sample console front end that builds on top of your library and implements a text-based interactive tic-tac-toe game running in the terminal.

Here’s what actual gameplay between two players might look like:

Generally, you may mix and choose the players from among a human player, a dummy computer player making moves at random, and a smart computer player sticking to the optimal strategy. You can also specify which player should make the first move, increasing their chances of winning or tying.

Later, you’ll be able to adapt your generic tic-tac-toe library for different platforms, such as a windowed desktop environment or a web browser . While you’ll only follow instructions on building a console application in this tutorial, you can find Tkinter and PyScript front end examples in the supporting materials.

Note: These front ends aren’t covered here because implementing them requires considerable familiarity with threading , asyncio , and queues in Python, which is beyond the scope of this tutorial. But feel free to study and play around with the sample code on your own.

The Tkinter front end is a streamlined version of the same game that’s described in a separate tutorial , which only serves as a demonstration of the library in a desktop environment:

Unlike the original, it doesn’t look as slick, nor does it allow you to restart the game easily. However, it adds the option to play against the computer or another human player if you want to.

The PyScript front end lets you or your friends play the game in a web browser even when they don’t have Python installed on their computer , which is a notable benefit:

If you’re adventurous and know a little bit of PyScript or JavaScript , then you could extend this front end by adding the ability to play online with another human player through the network. To facilitate the communication, you’d need to implement a remote web server using the WebSocket protocol, for instance. Take a look at a working WebSocket client and server example in another tutorial to get an idea of how that might work.

It’s worth noting that each of the three front ends demonstrated in this section merely implement a different presentation layer for the same Python library, which provides the underlying game logic and players. There’s no unnecessary redundancy or code duplication across them, thanks to the clear separation of concerns and other programming principles that you’ll practice in this tutorial.

The project that you’re going to build consists of two high-level components depicted in the diagram below:

Tic-Tac-Toe Architecture Diagram

The first component is an abstract tic-tac-toe Python library, which remains agnostic about the possible ways of presenting the game to the user in a graphical form. Instead, it contains the core logic of the game and two artificial players. However, the library can’t stand on its own, so you’re also going to create a sample front end to collect user input from the keyboard and visualize the game in the console using plain text.

You’ll start by implementing the low-level details of the tic-tac-toe library, and then you’ll use those to implement a higher-level game front end in a bottom-up fashion. When you finish this tutorial, the complete file structure resulting will look like this:

The frontends/ folder is meant to house one or more concrete game implementations, such as your text-based console one, while library/ is the home folder for the game library. You can think of both top-level folders as related yet separate projects.

Notice that your console front end contains the __main__.py file, making it a runnable Python package that you’ll be able to invoke from the command line using Python’s -m option. Assuming that you changed the current working directory to frontends/ after downloading the complete source code that you’ll be writing in this tutorial, you can start the game with the following command:

Remember that Python must be able to find the tic-tac-toe library, which your front end depends on, on the module search path. The best practice for ensuring this is by creating and activating a shared virtual environment and installing the library with pip . You’ll find detailed instructions on how to do this in the README file in the supporting materials.

The tic-tac-toe library is a Python package named tic_tac_toe consisting of two subpackages:

  • tic_tac_toe.game : A scaffolding designed to be extended by front ends
  • tic_tac_toe.logic : The building blocks of the tic-tac-toe game

You’ll dive deeper into each of them soon. The pyproject.toml file contains the metadata necessary for building and packaging the library. To install the downloaded library or the finished code that you’ll build in this tutorial into an active virtual environment, try this command:

During development, you can make an editable install using pip with the -e or --editable flag to mount the library’s source code instead of the built package in your virtual environment. This will prevent you from having to repeat the installation after making changes to the library to reflect them in your front end.

Okay, that’s what you’re going to build! But before you get started, check out the prerequisites.

This is an advanced tutorial touching on a wide range of Python concepts that you should be comfortable with in order to move on smoothly. Please use the following resources to familiarize yourself with or refresh your memory on a few important topics:

  • Object-oriented programming (OOP)
  • Inheritance and composition
  • Abstract classes
  • Data classes
  • Regular expressions

The project that you’re going to build relies solely on Python’s standard library and has no external dependencies. That said, you’ll need at least Python 3.10 or later to take advantage of the latest syntax and features leveraged in this tutorial. If you’re currently using an older Python release, then you can install and manage multiple Python versions with pyenv or try the latest Python release in Docker .

Lastly, you should know the rules of the game that you’ll be implementing. The classic tic-tac-toe is played on a three-by-three grid of cells or squares where each player places their mark, an X or an O, in an empty cell. The first player to place three of their marks in a row horizontally, vertically, or diagonally wins the game.

Step 1: Model the Tic-Tac-Toe Game Domain

In this step, you’ll identify the parts that make up a tic-tac-toe game and implement them using an object-oriented approach. By modeling the domain of the game with immutable objects , you’ll end up with modular and composable code that’s easier to test, maintain, debug, and reason about, among several other advantages.

For starters, open the code editor of your choice, such as Visual Studio Code or PyCharm , and create a new project called tic-tac-toe , which will also become the name of your project folder. Nowadays, most code editors will give you the option to create a virtual environment for your project automatically, so go ahead and follow suit. If yours doesn’t, then make the virtual environment manually from the command line:

This will create a folder named venv/ under tic-tac-toe/ . You don’t have to activate your new virtual environment unless you plan to continue working in the current command-line session.

Next, scaffold this basic structure of files and folders in your new project, remembering to use underscores ( _ ) instead of dashes ( - ) for the Python package in the src/ subfolder:

All of the files in the file tree above should be empty at this point. You’ll successively fill them with content and add more files as you go through this tutorial. Start by editing the pyproject.toml file located next to your src/ subfolder. You can paste this fairly minimal packaging configuration for your tic-tac-toe library into it:

You specify the required build tools, which Python will download and install if necessary, along with some metadata for your project. Adding the pyproject.toml file to the library lets you build and install it as a Python package into your active virtual environment.

Note: The pyproject.toml file is a standard configuration file using the TOML format for specifying minimum build system requirements for Python projects. The concept was introduced in PEP 518 and is now the recommended way of adding packaging metadata and configuration in Python. You’re going to need this to install the tic-tac-toe library into your virtual environment.

Open the terminal window and issue the following commands to activate your virtual environment if you haven’t already, and install the tic-tac-toe library using the editable mode:

Even though there’s no Python code in your library yet, installing it now with the --editable flag will let the Python interpreter import the functions and classes that you’ll be adding shortly straight from your project. Otherwise, every single time you made a change in your source code and wanted to test it, you’d have to remember to build and install the library into your virtual environment again.

Now that you have a general structure for your project, you can start implementing some code. By the end of this step, you’ll have all the essential pieces of a tic-tac-toe game in place, including the game logic and state validation, so you’ll be ready to combine them in an abstract game engine.

At the start of the game, each tic-tac-toe player gets assigned one of two symbols, either cross (X) or naught (O) , which they use to mark locations on the game board. Since there are only two symbols belonging to a fixed set of discrete values, you can define them within an enumerated type or enum . Using enums is preferable over constants due to their enhanced type safety, common namespace, and programmatic access to their members.

Create a new Python module called models in the tic_tac_toe.logic package:

You’ll use this file throughout the rest of this step to define tic-tac-toe domain model objects.

Now, import the enum module from Python’s standard library and define a new data type in your models:

The two singleton instances of the Mark class, the enum members Mark.CROSS and Mark.NAUGHT , represent the players’ symbols. By default, you can’t compare a member of a Python enum against its value. For instance, comparing Mark.CROSS == "X" will give you False . This is by design to avoid confusing identical values defined in different places and having unrelated semantics.

However, it may sometimes be more convenient to think about the player marks in terms of strings instead of enum members. To make that happen, define Mark as a mixin class of the str and enum.Enum types:

This is known as a derived enum , whose members can be compared to instances of the mixed-in type. In this case, you can now compare Mark.NAUGHT and Mark.CROSS to string values.

Note: Python 3.10 was the latest release at the time of writing this tutorial, but if you’re using a newer release, then you can directly extend enum.StrEnum , which was added to the standard library in Python 3.11:

Members of enum.StrEnum are also strings, which means that you can use them almost anywhere that a regular string is expected.

Once you assign a given mark to the first player, the second player must be assigned the only remaining and unassigned mark. Because enums are glorified classes, you’re free to put ordinary methods and properties into them. For example, you can define a property of a Mark member that’ll return the other member:

The body of your property is a single line of code that uses a conditional expression to determine the correct mark. The quotation marks around the return type in your property’s signature are mandatory to make a forward declaration and avoid an error due to an unresolved name. After all, you claim to return a Mark , which hasn’t been fully defined yet.

Note: Alternatively, you can postpone the evaluation of annotations until after they’ve been defined:

Adding a special __future__ import, which must appear at the beginning of your file, enables the lazy evaluation of type hints. You’ll use this pattern later to avoid the circular reference problem when importing cross-referencing modules.

In Python 3.11, you can also use a universal typing.Self type to avoid the forward declaration in type hints in the first place.

To reveal a few practical examples of using the Mark enum, expand the collapsible section below:

How to Use Mark Show/Hide

Before proceeding, make sure that you made the library accessible on the module search path by, for example, installing it into an active virtual environment, as shown earlier in the project overview :

You’ll use some of those techniques later in this tutorial.

You now have a way to represent the available markings that players will leave on the board to advance the game. Next, you’ll implement an abstract game board with well defined locations for those markings.

While some people play variants of tic-tac-toe with different numbers of players or different sizes of grids, you’ll stick with the most basic and classic rules. Recall that the game’s board is represented by a three-by-three grid of cells in the classic tic-tac-toe. Each cell can be empty or marked with either a cross or a naught.

Because you represent marks with a single character, you can implement the grid using a string of precisely nine characters corresponding to the cells. A cell can be empty, in which case you’ll fill it with the space character ( " " ), or it can contain the player’s mark. In this tutorial, you’ll store the grid in row-major order by concatenating the rows from top to bottom.

For example, with such a representation, you could express the three gameplays demonstrated before with the following string literals:

  • "OXXXXOOOX"
  • "OOOXXOXX "

To better visualize them, you can whip up and run this short function in an interactive Python interpreter session:

The function takes a string of cells as an argument and prints it onto the screen in the form of three separate rows carved out with the slice operator from the input string.

While using strings to represent the grid of cells is pretty straightforward, it falls short in terms of validating its shape and content. Other than that, plain strings can’t provide some extra, grid-specific properties that you might be interested in. For these reasons, you’ll create a new Grid data type on top of a string wrapped in an attribute:

You define Grid as a frozen data class to make its instances immutable so that once you create a grid object, you won’t be able to alter its cells. This may sound limiting and wasteful at first because you’ll be forced to make many instances of the Grid class instead of just reusing one object. However, the benefits of immutable objects , including fault tolerance and improved code readability, far outweigh the costs in modern computers.

By default, when you don’t specify any value for the .cells attribute, it’ll assume a string of exactly nine spaces to reflect an empty grid . However, you can still initialize the grid with the wrong value for cells, ultimately crashing the program. You can prevent this by allowing your objects only to exist if they’re in a valid state. Otherwise, they won’t be created at all, following the fail-fast and always-valid domain model principles.

Data classes take control of object initialization, but they also let you run a post-initialization hook to set derived properties based on the values of other fields, for example. You’ll take advantage of this mechanism to perform cell validation and potentially discard invalid strings before instantiating a grid object:

Your special .__post_init__() method uses a regular expression to check whether the given value of the .cells attribute is exactly nine characters long and contains only the expected characters—that is, "X" , "O" , or " " . There are other ways to validate strings, but regular expressions are very compact and will remain consistent with the future validation rules that you’ll add later.

Note: The grid is only responsible for validating the syntactical correctness of a string of cells, but it doesn’t understand the higher-level rules of the game. You’ll implement the validation of a particular cell combination’s semantics elsewhere once you gain additional context.

At this point, you can add a few extra properties to your Grid class, which will become handy when determining the state of the game:

The three properties return the current number of crosses, naughts, and empty cells, respectively. Because your data class is immutable, its state will never change, so you can cache the computed property values with the help of the @cached_property decorator from the functools module. This will ensure that their code will run at most once, no matter how many times you access these properties, for example during validation.

To reveal a few practical examples of using the Grid class, expand the collapsible section below:

How to Use Grid Show/Hide

Now you know how to use the Grid class.

Using Python code, you modeled a three-by-three grid of cells, which can contain a particular combination of players’ marks. Now, it’s time to model the player’s move so that artificial intelligence can evaluate and choose the best option.

An object representing the player’s move in tic-tac-toe should primarily answer the following two questions:

  • Player’s Mark: What mark did the player place?
  • Mark’s Location: Where was it placed?

However, in order to have the complete picture, one must also know about the state of the game before making a move. After all, it can be a good or a bad move, depending on the current situation. You may also find it convenient to have the resulting state of the game at hand so that you can assign it a score. By simulating that move , you’ll be able to compare it with other possible moves.

Note: A move object can’t validate itself without knowing some of the game details, such as the starting player’s mark, which aren’t available to it. You’ll check whether a given move is valid, along with validating a specific grid cell combination, in a class responsible for managing the game’s state.

Based on these thoughts, you can add another immutable data class to your models:

Please ignore the two forward declarations of the GameState class for the moment. You’ll define that class in the next section, using the type hint as a temporary placeholder.

Your new class is strictly a data transfer object (DTO) whose main purpose is to carry data, as it doesn’t provide any behavior through methods or dynamically computed properties. Objects of the Move class consist of the mark identifying the player who made a move, a numeric zero-based index in the string of cells, and the two states before and after making a move.

The Move class will be instantiated, populated with values, and manipulated by the missing GameState class. Without it, you won’t be able to correctly create the move objects yourself. It’s time to fix that now!

A tic-tac-toe game can be in one of several states, including three possible outcomes:

  • The game hasn’t started yet.
  • The game is still going on.
  • The game has finished in a tie.
  • The game has finished with player X winning.
  • The game has finished with player O winning.

You can determine the current state of a tic-tac-toe game based on two parameters:

  • The combination of cells in the grid
  • The mark of the starting player

Without knowing who started the game, you won’t be able to tell whose turn it is now and whether the given move is valid. Ultimately, you can’t properly assess the situation so that the artificial intelligence can make the right decision.

To fix that, begin by specifying the game state as another immutable data class consisting of the grid of cells and the starting player’s mark:

By convention, the player who marks the cells with crosses starts the game, hence the default value of Mark("X") for the starting player’s mark. However, you can change it according to your preference by supplying a different value at runtime.

Now, add a cached property returning the mark of the player who should make the next move:

The current player’s mark will be the same as the starting player’s mark when the grid is empty or when both players have marked an equal number of cells. In practice, you only need to check the latter condition because a blank grid implies that both players have zero marks in the grid. To determine the other player’s mark, you can take advantage of your .other property in the Mark enum.

Next up, you’ll add some properties for evaluating the current state of the game. For example, you can tell that the game hasn’t started yet when the grid is blank, or contains exactly nine empty cells:

This is where your grid’s properties come in handy. Conversely, you can conclude that the game has finished when there’s a clear winner or there’s a tie:

The .winner property, which you’ll implment in a bit, will return a Mark instance or None , whereas the .tie property will be a Boolean value. A tie is when neither player has won, which means there’s no winner, and all of the squares are filled, leaving zero empty cells:

Both the .game_over and .tie properties rely on the .winner property, which they delegate to. Finding a winner is slightly more difficult, though. You can, for example, try to match the current grid of cells against a predefined collection of winning patterns with regular expressions:

There are eight winning patterns for each of the two players, which you define using templates resembling regular expressions. The templates contain question-mark placeholders for the concrete player’s mark. You iterate over those templates and replace the question marks with both players’ marks to synthesize two regular expressions per pattern. When the cells match a winning pattern, you return the corresponding mark. Otherwise, you return None .

Knowing the winner is one thing, but you may also want to know the matched winning cells to differentiate them visually. In this case, you can add a similar property, which uses a list comprehension to return a list of integer indices of the winning cells:

You might be concerned about having a bit of code duplication between .winner and .winnning_cells , which violates the Don’t Repeat Yourself (DRY) principle, but that’s okay. The Zen of Python says that practicality beats purity , and indeed, extracting the common denominator would provide little value here while making the code less readable.

Note: It usually makes sense to start thinking about refactoring your code when there are at least three instances of a duplicated code fragment. There’s a high chance that you’ll need to reuse the same piece of code even more.

Your GameState is starting to look pretty good. It can correctly recognize all possible game states, but it lacks proper validation, making it prone to runtime errors. In the next few sections, you’ll rectify that by codifying and enforcing a few tic-tac-toe rules.

As with the grid, creating an instance of the GameState class should fail when the supplied combination of cells and the starting player’s mark don’t make sense. For example, it’s currently possible to create an invalid game state that doesn’t reflect genuine gameplay. You can test it yourself.

Start an interactive Python interpreter session in the virtual environment where you had previously installed your library, and then run the following code:

Here, you initialize a new game state using a grid comprising a syntactically correct string with the right characters and length. However, such a cell combination is semantically incorrect because one player isn’t allowed to fill the entire grid with their mark.

Because validating the game state is relatively involved, implementing it in the domain model would violate the single-responsibility principle and make your code less readable. Validation belongs to a separate layer in your architecture, so you should keep the domain model and its validation logic in two different Python modules without mixing their code. Go ahead and create two new files in your project:

You’ll store various helper functions in validators.py and a few exception classes in the exceptions.py file to decouple game state validation from the model.

For improved code consistency , you can extract the grid validation that you defined earlier in the __post_init__() method, move it into the newly created Python module, and wrap it in a new function:

Note that you replaced self.cells with grid.cells because you’re now referring to a grid instance through the function’s argument.

If you’re using PyCharm, then it might have started highlighting an unresolved reference to tic_tac_toe , which isn’t present on the search path for Python modules and packages. PyCharm doesn’t seem to recognize editable installs correctly, but you can fix that by right-clicking on your src/ folder and marking it as the so-called sources root in the project view:

You can have as many folders marked as sources roots as you want. Doing so will append their absolute paths to the PYTHONPATH environment variable managed by PyCharm. However, this won’t affect your environment outside of PyCharm, so running a script through the system’s terminal won’t benefit from marking those folders. Instead, you can activate the virtual environment with your library installed to import its code.

After extracting the grid validation logic, you should update the corresponding part in your Grid model by delegating the validation to an appropriate abstraction:

You import the new helper function and call it in your grid’s post-initialization hook, which now uses a higher-level vocabulary to communicate its intent. Previously, some low-level details, such as the use of regular expressions, were leaking into your model, and it wasn’t immediately clear what the .__post_init__() method does.

Unfortunately, this change now creates the notorious circular-reference problem between your model and validator layers, which mutually depend on each other’s bits. When you try to import Grid , you’ll get this error:

That’s because Python reads the source code from top to bottom. As soon as it encounters an import statement, it’ll jump to the imported file and start reading it. However, in this case, the imported validators module wants to import the models module, which hasn’t been fully processed yet. This is a very common problem in Python when you start using type hints.

The only reason you need to import models is because of a type hint in your validating function. You could get away without the import statement by surrounding the type hint with quotes ( "Grid" ) to make a forward declaration like before. However, you’ll follow a different idiom this time. You can combine the postponed evaluation of annotations with a special TYPE_CHECKING constant:

You import Grid conditionally. The TYPE_CHECKING constant is false at runtime , but third-party tools, such as mypy , will pretend it’s true when performing static type checking to allow the import statement to run. However, because you no longer import the required type at runtime, you must now use forward declarations or take advantage of from __future__ import annotations , which will implicitly turn annotations into string literals.

Note: The __future__ import was originally intended to make the migration from Python 2 to Python 3 more seamless. Today, you can use it to enable various language features planned for future releases. Once a feature becomes part of the standard Python distribution and you don’t need to support older language versions, you can remove that import.

With all this plumbing in place, you’re finally ready to constrain the game state to comply with the tic-tac-toe rules. Next up, you’ll add a few GameState validation functions to your new validators module.

In order to reject invalid game states, you’ll implement a familiar post-initialization hook in your GameState class that delegates the processing to another function:

The validating function, validate_game_state() , receives an instance of the game state, which in turn contains the grid of cells and the starting player. You’re going to use this information, but first, you’ll split the validation into a few smaller and more focused stages by delegating bits of the state further down in your validators module:

Your new helper function serves as an entry point to the game state validation by calling a few subsequent functions that you’ll define in just a bit.

To prevent instantiating a game state with an incorrect number of a player’s marks in the grid, such as the one you stumbled on before, you must take the proportion of naughts to crosses into account:

At any time, the number of marks left by one player must be either the same or greater by exactly one compared to the number of marks left by the other player. Initially, there are no marks, so the number of Xs and Os is equal to zero. When the first player makes a move, they’ll have one more mark than their opponent. But, as soon as the other player makes their first move, the proportion evens out again, and so on.

To signal an invalid state, you raise a custom exception defined in another module:

It’s customary to have empty classes extend the built-in Exception type in Python without specifying any methods or attributes in them. Such classes exist solely for their names, which convey enough information about the error that occurred at runtime. Notice that you don’t need to use the pass statement or the ellipsis literal ( ... ) as a class body placeholder if you use a docstring , which can provide additional documentation.

Another game state inconsistency related to the number of marks left on the grid has to do with the starting player’s mark , which may be wrong:

The player who left more marks on the grid is guaranteed to be the starting player. If not, then you know that something must have gone wrong. Because you defined Mark as an enum derived from str , you can directly compare the starting player’s mark to a string literal.

Finally, there can only be one winner , and depending on who started the game, the ratio of Xs ans Os left on the grid will be different:

A starting player has an advantage, so when they win, they’ll have left more marks than their opponent. Conversely, the second player is at a disadvantage, so they can only win the game by making an equal number of moves as the starting player.

You’re almost done with encapsulating the tic-tac-toe game’s rules in Python code, but there’s still one more important piece missing. In the next section, you’ll write code to systematically produce new game states by simulating players’ moves.

The last property that you’ll add to your GameState class is a fixed list of possible moves, which you can find by filling the remaining empty cells in the grid with the current player’s mark:

If the game’s over, then you return an empty list of moves. Otherwise, you identify the locations of empty cells using a regular expression, and then make a move to each of those cells. Making a move creates a new Move object, which you append to the list without mutating the game state.

This is how you construct a Move object:

A move isn’t allowed if the target cell is already occupied by either your or your opponent’s mark, in which case you raise an InvalidMove exception. On the other hand, if the cell is empty, then you take a snapshot of the current player’s mark, the target cell’s index, and the current game state while synthesizing the following state.

Don’t forget to define the new exception type that you imported:

That’s it! You’ve just gotten yourself a pretty solid domain model of the tic-tac-toe game, which you can use to build interactive games for various front ends. The model encapsulates the game’s rules and enforces its constraints.

How to Use GameState Show/Hide

Now you know how the various GameState attributes work and how to combine them with other domain model objects.

In the next section, you’ll build an abstract game engine and your first artificial player .

Step 2: Scaffold a Generic Tic-Tac-Toe Game Engine

At this point, you should have all the domain models defined for your tic-tac-toe library. Now, it’s time to build a game engine that’ll take advantage of these model classes to facilitate tic-tac-toe gameplay.

Go ahead and create three more Python modules inside the tic_tac_toe.game package now:

The engine module is the centerpiece of the virtual gameplay, where you’ll implement the game’s main loop. You’ll define abstract interfaces that the game engine uses, along with a sample computer player, in the players and renderers modules. By the end of this step, you’ll be set to write a tangible front end for the tic-tac-toe library.

At the very minimum, to play a tic-tac-toe game, you need to have two players, something to draw on, and a set of rules to follow. Fortunately, you can express these elements as immutable data classes, which take advantage of the existing domain model from your library. First, you’ll create the TicTacToe class in the engine module:

Both Player and Renderer will be implemented in the following sections as Python’s abstract base classes , which only describe the high-level interface for your game engine. However, they’ll eventually get replaced with concrete classes, some of which may come from an externally defined front end. The player will know what move to make, and the renderer will be responsible for visualizing the grid.

To play the game, you must decide which player should make the first move , or you can assume the default one, which is the player with crosses. You should also begin with a blank grid of cells and an initial game state :

The engine requests that the renderer update the view and then uses a pull strategy to advance the game by asking both players to make their moves in alternating rounds. These steps are repeated in an infinite loop until the game is over.

GameState only knows about the current player’s mark, which can be either X or O, but it doesn’t know about the specific player objects that were assigned those marks. Therefore, you need to map the current mark to a player object using this helper method:

Here, you compare enum members by their identities using Python’s is operator. If the current player’s mark determined by the game state is the same as the mark assigned to the first player, then that’s the player who should be making the next move.

Both players supplied to the TicTacToe object should have opposite marks. Otherwise, you wouldn’t be able to play the game without violating its rules. So, it’s reasonable to validate the players’ marks when instantiating the TicTacToe class:

You add a post-initialization hook to your data class and call another validation function that you have to add in your validators module:

You use the identity comparison again to check both players’ marks and prevent the game from starting when both players use the same mark.

There’s one more thing that can go wrong. Because it’s up to the players, including human players, to decide what move they make, their choice could be invalid. Currently, your TicTacToe class catches the InvalidMove exception but doesn’t do anything useful with it other than ignore such a move and ask the player to make a different choice. It would probably help to let the front end handle errors by, for example, showing a suitable message:

To let the front end decide how to take care of an invalid move, you expose a hook in your class by introducing an optional .error_handler callback , which will receive the exception. You define the callback’s type using a type alias , making its type declaration more concise. The TicTacToe game will trigger this callback in case of an invalid move, as long as you provide the error handler.

Having implemented an abstract tic-tac-toe game engine, you can proceed to code an artificial player. You’ll define a generic player interface and implement it with a sample computer player that makes moves at random.

First, define an abstract Player , which will be the base class for concrete players to extend:

An abstract class is one that you can’t instantiate because its objects wouldn’t stand on their own. Its only purpose is to provide the skeleton for concrete subclasses. You can mark a class as abstract in Python by setting its metaclass to abc.ABCMeta or extending the abc.ABC ancestor.

Note: Using the metaclass argument instead of extending the base class is slightly more flexible, as it doesn’t affect your inheritance hierarchy. This is less important in languages like Python, which support multiple inheritance. Anyway, as a rule of thumb, you should favor composition over inheritance whenever possible.

The player gets assigned a Mark instance that they’ll be using during the game. The player also exposes a public method to make a move, given a certain game state:

Notice how the public .make_move() method defines a universal algorithm for making a move, but the individual step of getting the move is delegated to an abstract method, which you must implement in concrete subclasses. Such a design is known as the template method pattern in object-oriented programming.

Making a move entails checking if it’s the given player’s turn and whether the move exists. The .get_move() method returns None to indicate that no more moves are possible, and the abstract Player class uses the Walrus operator ( := ) to simplify the calling code.

To make the game feel more natural, you can introduce a short delay for the computer player to wait before choosing their move. Otherwise, the computer would make its moves instantly, unlike a human player. You can define another, slightly more specific abstract base class to represent computer players:

ComputerPlayer extends Player by adding an additional member, .delay_seconds , to its instances, which by default is equal to 250 milliseconds. It also implements the .get_move() method to simulate a certain wait time, and then calls another abstract method specific to computer players.

Having an abstract computer player data type enforces a uniform interface, which you can conveniently satisfy with a few lines of code. For example, you can implement a computer player picking moves at random in the following way:

You use choice() to pick a random element from a list of possible moves. If there are no more moves in the given game state, then you’ll get an IndexError because of an empty list, so you catch it and return None instead.

You now have two abstract base classes, Player and ComputerPlayer , as well as one concrete RandomComputerPlayer , which you’ll be able to use in your games. The only remaining element of the equation before you can put those classes into action is the abstract renderer, which you’ll define next.

Giving the tic-tac-toe grid a visual form is entirely up to the front end, so you’ll only define an abstract interface in your library:

This could’ve been implemented as a regular function because the renderer exposes only a single operation while getting the whole state through an argument. However, concrete subclasses may need to maintain an additional state, such as the application’s window, so having a class may come in handy at some point.

Okay, you have the tic-tac-toe library with a robust domain model, an engine encapsulating the game rules, a mechanism to simulate moves, and even a concrete computer player. In the next section, you’ll combine all the pieces together and build a game front end, letting you finally see some action!

Step 3: Build a Game Front End for the Console

So far, you’ve been working on an abstract tic-tac-toe game engine library, which provides the building blocks for the game. In this section, you’ll bring it to life by coding a separate project that relies on this library. It’s going to be a bare-bones game running in the text-based console.

The most important aspect of any game front end is providing visual feedback to the players through a graphical interface . Because you’re constrained to the text-based console in this example, you’ll take advantage of ANSI escape codes to control things like text formatting or placement.

Create the renderers module in your console front end and define a concrete class that extends the tic-tac-toe’s abstract renderer in it:

In case you’re using Visual Studio Code , and it doesn’t resolve the imports, try closing and reopening the editor. The ConsoleRenderer class overrides .render() , the only abstract method responsible for visualizing the game’s current state. In this case, you start by clearing the screen’s content using a helper function, which you can define below the class:

The string literal "\033" represents a non-printable Esc character, which starts a special code sequence . The letter c that follows encodes the command to clear the screen. Note that the print() function automatically ends the text with a newline character. To avoid adding an unnecessary blank line, you must disable this by setting the end argument.

When there’s a winner, you’ll want to distinguish their winning marks with blinking text . You can define another helper function to encode blinking text using the relevant ANSI escape code:

Here, you wrap the supplied text with opening and closing ANSI escape codes in Python’s f-string .

To render the tic-tac-toe grid filled with players’ marks, you’ll format a multiline template string and use the textwrap module to remove the indentation:

The print_solid() function takes a sequence of cells and prints them with an additional gutter around the top-left corner. It contains numbered rows and columns indexed by letters. For example, a partially filled tic-tac-toe grid may look like this on the screen:

The gutter will make it easier for the player to specify the coordinates of the target cell where they want to put their mark.

If there’s a winner , you’ll want to blink some of their cells and print a message stating who won the game. Otherwise, you’ll print a solid grid of cells and optionally inform the players that there are no winners in case of a tie :

Your messages contain special syntax for name aliases of Unicode characters, including emojis , in order to make the output look more colorful and exciting. For example, "\N{party popper}" will render the 🎉 emoji. Note that you call yet another helper function, print_blinking() , which you must define now:

This new function takes the sequence of cells and the numeric positions of those which should be rendered using blinking text. Then, it makes a mutable copy of the cells, overwrites the specified cells with blinking ANSI escape codes, and delegates the rendering to print_solid() .

At this point, you can test your custom renderer using two computer players built into the tic-tac-toe library. Save the following code in a file named play.py located in the frontends/ folder:

When you run this script , you’ll see two artificial players making random moves, leading to different outcomes each time:

While it’s interesting to look at their gameplay, there’s no interactivity whatsoever. You’re going to change that now by letting human players decide what moves to make.

At the end of this section, you’ll be able to play a tic-tac-toe match between a human and a computer player or two human players , in addition to the two computer players you just saw. A human player will use the keyboard interface to specify their moves.

You can define a new concrete player class in your console front end, which will implement the abstract .get_move() method specified in the library. Create the front end’s players module and fill it with the following content:

If the game has finished, then you return None to indicate that no moves were possible. Otherwise, you keep asking the player for a valid move until they provide one and make that move. Because the human player types cell coordinates like A1 or C3 , you must convert such text to a numeric index with the help of the grid_to_index() function:

The function uses regular expressions to extract the numeric row and column so that you can calculate the corresponding index in the flat sequence of cells.

You can now modify your test script by importing and instantiating ConsolePlayer :

Running this script will allow you to play as X against the computer. Unfortunately, there’s no convenient way of changing the players or stating who should start the game, because this information is baked into the code. Next up, you’ll add a command-line interface to fix that.

You’re almost done building your tic-tac-toe front end. However, it’s time to add the finishing touches and turn it into a playable game by implementing a useful command-line interface using the argparse module. That way, you’ll be able to choose the player types and the starting mark before running the game.

The entry point to your console front end is the special __main__.py module, which makes the containing package runnable through the python command. Because it’s customary to put minimal wrapper code in it, you’ll keep the module lightweight by delegating the processing to a function imported from another module:

This makes the code that’s defined in cli.py more reusable across many places and easier to test in isolation. Here’s how that code might look:

You import the game engine, your new console renderer, and a helper function, parse_argse() , which will be able to read command-line arguments and, based on them, return two player objects and the starting player’s mark.

To implement the parsing of arguments, you can start by defining the available player types as a Python dictionary , which associates everyday names like human with concrete classes extending the abstract Player :

This will make it more straightforward to add more player types in the future. Next, you can write a function that’ll use the argparse module to get the expected arguments from the command line:

The code above translates to the following three optional arguments, all of which have default values:

Argument Default Value Description
Assigns X to the specified player
Assigns O to the specified player
Determines the starting player’s mark

At this point, the function parses those arguments and stores their values as strings in a special NameSpace object under the attributes named .player_x , .player_o , and .starting_mark , respectively. However, the function is expected to return a tuple consisting of custom data types instead of strings. To make the function’s body comply with its signature, you can map strings provided by the user to the respective classes using your dictionary:

You translate the user-supplied names to concrete player classes. If the starting player’s mark is different from the default one, then you swap the two players before returning them from the function.

To make the code slightly cleaner and more expressive, you may replace the generic tuple with a typed named tuple :

First, you define a typing.NamedTuple subclass comprising precisely three named and typed elements. You then return an instance of your named tuple instead of a generic tuple. Doing so gives you additional type safety and access to the tuple’s elements by name as well as by index.

To play against another human, you can run your console front end with these arguments:

If you’d like to try your chances against the computer, then replace the value of either the -X or -O option with random , which is currently the only computer player type available. Unfortunately, it isn’t particularly challenging to play against a player making moves at random. In the next step, you’ll implement a more advanced computer player leveraging the minimax algorithm , which makes the computer practically undefeatable.

Step 4: Equip the Computer With Artificial Intelligence

You’ve reached the final step in this tutorial, which involves creating another computer player, this one equipped with basic artificial intelligence. Specifically, it’ll use the minimax algorithm under the surface to make the most optimal move in every possible situation in any turn-based zero-sum game like tic-tac-toe.

Note: Mastering the details of the minimax algorithm isn’t your focus in this tutorial. But, if you’d like to learn more about it, then check out Minimax in Python: Learn How to Lose the Game of Nim , which uses a more straightforward game of Nim as an example.

Before implementing the algorithm, you have to invent a way of assessing the game’s score, which will become the deciding factor behind choosing the best move. You’ll do that by introducing an absolute scale of numeric values indicating how well both players are doing.

For simplicity, you’ll consider static evaluation of a finished game. There are three possible outcomes of the game, which you can assign arbitrary numeric values, for example:

  • Player loses: -1
  • Player ties: 0
  • Player wins: 1

The protagonist player whose score you’ll evaluate is known as the maximizing player because they try to maximize the game’s overall score. Therefore, greater values should correspond to better outcomes, as viewed from their perspective. The minimizing player , on the other hand, is their opponent, who tries to lower the score as much as possible. After all, they win when your player loses, while a tie can be equally good or bad for both players.

Once you determine the maximizing and minimizing players, the scale remains absolute, meaning you don’t need to flip the sign when evaluating your opponent’s moves.

You can express this numeric scale in Python code by adding the following method to your GameState model in the tic-tac-toe library:

Because this is a static evaluation, you can only determine the score when the game is over. Otherwise, you raise an UnknownGameScore exception, which you must add to the exceptions module in the library:

Knowing the score of a finished game isn’t that helpful when you want to make an informed decision about choosing a move up front. However, it’s the first step toward finding the best possible sequence of moves leading up to winning—or tying the game, in the worst-case scenario. Next, you’ll use the minimax algorithm to calculate the score in any game state.

When you have several moves to choose from, you want to pick one that’ll increase your expected score. At the same time, you want to avoid moves that could potentially shift the game’s score in favor of your opponent. The minimax algorithm can help with that by using the min() and max() functions to minimize your opponent’s maximum gain while maximizing your minimum payoff.

If that sounds complicated, then have a look at a graphical visualization of tic-tac-toe gameplay below.

When you imagine all possible game states as a game tree , choosing the best move boils down to searching for the most optimal path in such a weighted graph , starting from the current node. The minimax algorithm propagates the scores evaluated statically for the leaf nodes , which correspond to finished games, by bubbling them up in the game tree. Either the minimum or the maximum score gets propagated at each step, depending on whose turn it is.

You can visualize this process using a concrete example of the final three turns in a game of tic-tac-toe. Below, you’ll find a small segment of the tic-tac-toe game tree illustrating the possible moves of the maximizing player X, whose turns are depicted in green:

Tic-Tac-Toe Game Tree With Propagated Scores

The minimax algorithm starts by recursively exploring the tree to look ahead and find all the possible game outcomes. Once those are found, it computes their scores and backtracks to the starting node. If it’s the maximizing player’s turn that leads to the next position, then the algorithm picks the maximum score at that level. Otherwise, it picks the minimum score, assuming the opponent will never make mistakes.

In the game tree above, the leftmost branch results in an immediate win for the maximizing player, so the connecting edge has the highest weight. Choosing the middle branch could also lead to a victory, but the minimax algorithm pessimistically indicates the worst-case scenario, which is a tie. Finally, the branch on the right almost certainly represents a losing move.

Create a new minimax module in the tic-tac-toe library and implement the algorithm using the following sleek Python expression:

The minimax() function returns the score associated with the move passed as an argument for the indicated maximizing player. If the game has finished, then you calculate the score by performing the static evaluation of the grid. Otherwise, you choose either the maximum or the minimum score, which you find with recursion for all the possible moves at the current position.

Note: The placement of the minimax module in your project’s directory tree is somewhat subjective because it would work equally well when defined elsewhere. However, one could argue that it logically belongs to the game’s logic layer since it only depends on the domain model.

As long as you made an editable install of the tic-tac-toe library in your virtual environment, you’ll be able to test your new function in an interactive Python interpreter session:

The computed scores correspond to the edge weights in the game tree that you saw before. Finding the best move is only a matter of choosing the one with the highest resulting score. Note that there can sometimes be multiple alternative paths to a winning outcome in the game tree.

In the next section, you’ll create another concrete computer player, which will leverage the minimax algorithm, and then you’ll use it in your console front end.

The minimax algorithm calculates the score associated with a particular move. To find the best move in a given game state, you can sort all possible moves by score and take the one with the highest value. By doing that, you’ll use AI to create an unbeatable tic-tac-toe player with Python.

Go ahead and define the following function in your tic-tac-toe library’s minimax module:

The find_best_move() function takes some game state and returns either the best move for the current player or None to indicate that no more moves are possible. Note the use of a partial function to freeze the value of the maximizer argument, which doesn’t change across minimax() invocations. This lets you use the bound_minimax() function, which expects exactly one argument, as the ordering key.

Note: Python’s functools.partial() is a factory that produces a new function with fewer parameters by prepopulating one or more of the original function’s arguments with concrete values. Unlike manually defining such a wrapper function when writing code, the factory can do this dynamically at runtime and offers much more concise syntax.

Next, add a new computer player in the tic-tac-toe library’s players module. This player will use the find_best_move() helper function that you’ve just created:

This computer player will always try to find the best tic-tac-toe move with AI and Python. However, to make the game less predictable and reduce the amount of computation, you can let it pick the first move randomly before running the expensive minimax algorithm. You’ve already implemented the logic for choosing a random move in RandomComputerPlayer , defined above. Now, it would help to extract that common logic into a reusable component.

Go ahead and modify the code of both the random and minimax computer players:

You call the .make_random_move() method on the game state in both classes. You need to define this new method to choose one of the possible moves using Python’s random module:

The final step is to use the new computer player in your front end. Open the args module in the console front end project, and import MinimaxComputerPlayer :

You add the new player type to the mapping of names and use the minimax computer player as the default opponent of the human player.

Okay, you have three kinds of players to choose from now. You can take your console front end for the ultimate test drive by selecting different players to try their chances against each other. For example, you can pick two minimax computer players:

In this case, you should expect the game to always end in a tie since both players use the optimal strategy.

One thing you may notice when requesting at least one minimax player is rather poor performance, especially at the beginning of the game. That’s because building the entire game tree, even for a game as relatively basic as tic-tac-toe, is very costly. You’ll explore a few performance optimization possibilities in the Next Steps .

Congratulations! You’ve reached the end of this long journey. Don’t forget about the supporting materials, which contain additional code that wasn’t covered in the tutorial. The materials include two other front ends and some performance tricks, which make the minimax player make their moves instantly. You can download this code by clicking the link below:

You did a fantastic job completing this detailed step-by-step tutorial! You’ve built a front-end-agnostic tic-tac-toe library with the game’s core logic and two artificial computer players , including an unbeatable one leveraging the minimax algorithm . You also created a sample front end that renders the game in the text-based console and takes input from a human player .

Along the way, you followed good programming practices , including object-oriented design with elements of the functional paradigm , and took advantage of the latest enhancements in the Python language.

In this tutorial, you’ve learned how to:

  • Implement artificial players, including one based on the minimax algorithm

If you haven’t already done so, click the link below to download the complete source and some bonus code for the project that you’ve been building in this tutorial:

Having a generic Python tic-tac-toe library with the game’s core logic and AI lets you focus on building alternative front ends that can leverage different graphical interfaces. You’ve built a text-based console front end for tic-tac-toe in this tutorial, while the supporting materials contain examples of other presentation layers. Maybe you’ll want to make one for Jupyter Notebook or a mobile phone using Kivy or another Python framework.

An important area for improvement is the performance bottleneck stemming from the brute-force nature of the minimax algorithm , which checks all possible game states. There are several ways in which you can cut down the number of computations and speed up the process:

  • A heuristic: Instead of exploring the entire depth of the tree, you can stop at a designated level and estimate a rough score with a heuristic . It’s worth noting that this may sometimes give suboptimal results.
  • Caching: You can precompute the entire game tree up front, which would be a one-time effort requiring a lot of resources. Later, you’d be able to load the lookup table (LUT) into the memory and get the score instantly for every possible game state.
  • Alpha-beta pruning: It’s possible to dismiss a significant portion of the nodes in the game tree as bad choices when exploring it with the minimax algorithm. You can employ a slight modification to the minimax algorithm, known as the alpha-beta pruning technique. In short, it keeps track of the better options already available without entering branches guaranteed to offer worse choices.

Do you have other ideas for using or extending the tic-tac-toe library? Share them in the comments below!

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Bartosz ZaczyƄski

Bartosz ZaczyƄski

Bartosz is a bootcamp instructor, author, and polyglot programmer in love with Python. He helps his students get into software engineering by sharing over a decade of commercial experience in the IT industry.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Aldren Santos

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal . Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session . Happy Pythoning!

Keep Learning

Related Topics: advanced best-practices gamedev gui projects python

Recommended Video Course: Create a Tic-Tac-Toe Python Game Engine With an AI Player

Keep reading Real Python by creating a free account or signing in:

Already have an account? Sign-In

Almost there! Complete this form and click the button below to gain instant access:

Build a Tic-Tac-Toe Game Engine With an AI Player in Python (Source Code)

🔒 No spam. We take your privacy seriously.

game assignment in python

Baltimore Orioles | Orioles designate reliever Dillon Tate for…

Share this:.

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)

Baltimore Sun eNewspaper

  • College Sports
  • High School Sports
  • Horse Racing

Baltimore Orioles

Baltimore orioles | orioles designate reliever dillon tate for assignment, claim of forrest wall off waivers, the 30-year-old right-hander posted a 4.59 era in 29 games for baltimore this season.

Orioles reliever Dillon Tate has been designated for assignment. (Kenneth K. Lam/Staff)

LOS ANGELES — The Orioles claimed outfielder Forrest Wall off waivers Wednesday and designated reliever Dillon Tate for assignment in a corresponding move, the club announced. Wall, who was optioned to Triple-A Norfolk, will be postseason eligible for Baltimore since he was acquired ahead of the Sept. 1 deadline.

Tate, 30, posted a 4.59 ERA in 29 games for the Orioles this season, his first year back on the mound after missing the entire 2023 campaign with elbow and forearm injuries. The right-hander was a key setup man in the Orioles’ bullpen in 2022 with a 3.05 ERA in 67 appearances, but he was unable to return to form as Baltimore shuttled him back and forth between the majors and minor leagues. Tate will be placed on outright waivers, giving the other 29 MLB teams a chance to claim him.

“Last year was really tough for him, missing all of the year,” manager Brandon Hyde said. “I thought spring training, he was trying to find the stuff that he had when he was really lights out for us two years ago and a big part of our bullpen, and you saw the mid-to-high 90s sinker that had a lot of power behind it. I’m hoping for the best for D-Tate because I know how hard he’s worked here to kind of get back to that form and hope he latches on or we keep him in the organization, and he’s got a lot of years left.”

He’s replaced on the Orioles’ 40-man roster by Wall, a 2014 first-round pick of the Colorado Rockies who has spent time with five organizations. Wall has 50 career plate appearances at the big league level with the Miami Marlins and Atlanta Braves, hitting .311 with one home run and nine stolen bases. The 28-year-old is slashing .282/.380/.396 in 64 Triple-A games this season.

With prospect Heston Kjerstad nursing a concussion and on the injured list, Wall is the lone healthy outfielder in Norfolk currently on the Orioles’ 40-man roster. Hyde said Wednesday that Kjerstad is ramping up baseball activities but he wasn’t ready to commit to a timetable for his return.

More in Baltimore Orioles

Orioles rookie Cade Povich was struggling in the big leagues. So he went Baltimore's best pitcher — Corbin Burnes — for answers.

Baltimore Orioles | Looking for answers, Orioles rookie Cade Povich turned to Corbin Burnes

Shohei Ohtani hit a leadoff homer off Corbin Burnes and the Dodgers beat the Orioles, 6-4, in Los Angeles on Wednesday night.

Baltimore Orioles | Corbin Burnes, Orioles’ defense fall flat in 6-4 loss to Shohei Ohtani’s Dodgers

Orioles infielder Jorge Mateo, who has been out since July 23, will miss the rest of the 2024 season after undergoing Tommy John elbow reconstruction.

Baltimore Orioles | Orioles’ Jorge Mateo to miss rest of season after undergoing elbow surgery

The Orioles' Eloy Jiménez, a former Silver Slugger, is relying on Anthony Santander and an "awesome attitude" to get his career back on track.

Baltimore Orioles | Orioles’ Eloy JimĂ©nez making mark with ‘awesome attitude’ and Anthony Santander’s mentorship

IMAGES

  1. How to Make A Simple Game in Python (For Beginners)

    game assignment in python

  2. Battleship Game Code In Python

    game assignment in python

  3. Tetris Game In Python Code

    game assignment in python

  4. Snake Game In Python

    game assignment in python

  5. Puzzle Game In Python

    game assignment in python

  6. Complete Racing Game In Python Using PyGame

    game assignment in python

VIDEO

  1. Match Game

  2. Mastering Python Easily Using A Game?

  3. Week 3 graded assignment python #python #iitm

  4. "Mastering Assignment Operators in Python: A Comprehensive Guide"

  5. NPTEL Python for Data Science Week1 Assignment 1 Solution July 2024

  6. NPTEL Week 2 Assignment Python for Data Science By Prof. Ragunathan Rengasamy IIT Madras

COMMENTS

  1. Make Your First Python Game: Rock, Paper, Scissors!

    You don't necessarily need to create a function for the conditional check to play again, but you can if you'd like. You can start by importing random if you haven't already and defining your Action class: Python. import random from enum import IntEnum class Action(IntEnum): Rock = 0 Paper = 1 Scissors = 2.

  2. PyGame: A Primer on Game Programming in Python

    Lines 11 and 12 set up a game loop to control when the program ends. You'll cover game loops later on in this tutorial. Lines 15 to 17 scan and handle events within the game loop. You'll get to events a bit later as well. In this case, the only event handled is pygame.QUIT, which occurs when the user clicks the window close button.

  3. Easy Games in Python

    1. A Quiz Game in Python. This is a very simple text-based game in python. It a small quiz which you can make for yourself as well or your friends. We do not need to import any modules for this game which makes it easier! Try it yourself 😉. Here are use: if-else statement - For checking answers.

  4. Build a Tic-Tac-Toe Game With Python and Tkinter

    Step 1: Set Up the Tic-Tac-Toe Game Board With Tkinter. Ensure the Right Tkinter Version. Create a Class to Represent the Game Board. Step 2: Set Up the Tic-Tac-Toe Game Logic in Python. Define Classes for the Players and Their Moves. Create a Class to Represent the Game Logic. Set Up the Abstract Game Board.

  5. Create a Chess Game in Python Step-by-Step (Source Code)

    Now that your environment is set up, let's move on to creating our Python chess game. 3. Python Chess Game Tutorial with Pygame. Initializing the Chessboard. In this section, we'll start building the chessboard. We'll create a graphical interface using Pygame and set up the initial chessboard layout.

  6. Pygame Examples Tutorial

    Once the installation is complete, try creating a simple Pygame window. Let's start by importing Pygame and initiating it: import pygame. pygame.init() Now, let's create a display: win = pygame.display.set_mode( (500, 500)) This will create a window of width 500 and height 500. Note that the dimensions are passed as a tuple.

  7. Python Game Development Libraries

    PyGame. Pygame offers a robust and flexible framework for creating games in Python, making it an excellent choice for both beginners and experienced developers alike. Its rich feature set, cross-platform compatibility, and active community support make it a popular choice for game development projects of all sizes and complexities.

  8. PyGame Tutorial

    Pygame is a special tool that helps people to make fun and exciting video games using the Python. In PyGame, you can create your own computer game world using a set of tools. It includes computer graphics and sound libraries designed to be used with the Python programming language. Release date: 28 October 2000.

  9. Python Game Development 101: Create Games With Python

    The Making Games book uses game examples from the PyGame library to teach you how to make similar games. The goal of this tutorial is to give you a whole new batch of ideas for using Python software to develop your games. So even if you know Python and PyGame but you need ideas, you could give this book a skim.

  10. Tic-tac-toe using Python

    Step 1: Tic-tac-toe Design. We will be playing Tic-tac-toe on the command line, therefore, the first thing we have to do is create a design for our tic-tac-toe. Tic-tac-toe Design. If a player has to mark a particular box, he must enter the corresponding number shown in the grid.

  11. How to Create a Text Based Adventure Game in Python

    Create a new file called "AdventureGame.py", to store the code for your Python adventure game. In the file, add the main starting function. The function will include a brief opening story to welcome the player to the Python text-based adventure game. It will then call another function called introScene () .

  12. Creating a high and low game in python and need a lot of help!

    Start with the variables high = 1000, low = 1, and tries = 1. While high is greater than low. Guess the average of high and low. Ask the user to respond to the guess. Handle the four possible outcomes: If the guess was right, print a message that tries guesses were required and quit the program. If the guess was too high, print a message that ...

  13. Balloon Archer game in Python using the Pygame module

    The Balloon Archer game can be played in Python using keyboard controls. These controls are as follows: Use left/right and up/down arrows to move the archer. Use the space bar to shoot the arrow. Use 'r' or 'q' to restart or quit the game.

  14. Create Snake Game in Python

    import random. Code Explanation: Import pygame: It is used to import a set of python modules designed to write video games. Import random: It imports the module which generates pseudo-random variables. 3. Creating the snake game window: x = pygame.init() width_of_screen = 900. height_of_screen = 600.

  15. How To Code a Simple Number Guessing Game in Python

    Putting it all together. Now our Python script looks like so: # main.py. import random # define range and max_attempts. lower_bound = 1 upper_bound = 1000 max_attempts = 10 # generate the secret number. secret_number = random.randint(lower_bound, upper_bound) # Get the user's guess.

  16. How to Create a Tic-Tac-Toe Game in Python?

    Write a function to start the game. Select the first turn of the player randomly. Write an infinite loop that breaks when the game is over (either win or draw). Show the board to the user to select the spot for the next move. Ask the user to enter the row and column number.

  17. Python Game Development

    Python Game Development Tutorials. Creating your own computer games in Python is a great way to learn the language. To build a game, you'll need to use many core programming skills. The kinds of skills that you'll see in real-world programming. In game development, you'll use variables, loops, conditional statements, functions, object ...

  18. How to Make a Tic Tac Toe Game in Python with Code Example

    Building a Tic-Tac-Toe Game in Python: A Step-by-Step Guide. Tic-Tac-Toe, a classic and timeless game, is a perfect starting point for beginners diving into game development with Python. In this step-by-step guide, we will walk through the process of creating a simple yet functional Tic-Tac-Toe game using Python. By the end of this tutorial ...

  19. Python Exercises, Practice, Challenges

    These free exercises are nothing but Python assignments for the practice where you need to solve different programs and challenges. All exercises are tested on Python 3. Each exercise has 10-20 Questions. The solution is provided for every question. These Python programming exercises are suitable for all Python developers.

  20. Create a simple quiz game program in python with score

    In this post, you will learn how to create a simple quiz game program in python with a proper explanation and algorithm. this python program is considered as a mini-project for beginners and also helps them to boost their knowledge and confidence (this project gives you the confidence to learn more and more things) but before writing the program let's understand the algorithm for a python ...

  21. Python

    Download the package from github. Unzip into your Lib folder of python (i.e. C:\Python27\Lib) - this is just good practice. Navigate to folder in cmd and run the file named Setup.py by typing python Setup.py install. This should be all the setup you need to get the code working.

  22. Why Padres' Fernando Tatis Jr. Might Not Need a Rehab Assignment

    "It's more set up as simulated games. We have a defense and a pitcher. It's like a game but in a controlled setting. He can get a lot of at-bats and see a lot of pitches from right-handers ...

  23. Defining a symbolic syntax for referring to assignment targets

    __target_text__ could replace @'' for both identifier assignment and tuple assignment ( __target_name__ wouldn't match the latter use case) Sounds good indeed. With the name __target_text__ we wouldn't have to worry about a plural form. I doubt you could reasonably use that form to map function parameters to local variables of the same name ...

  24. NL West Rivals Lose Two Starting Pitchers to IL Ahead of Series Vs Padres

    The Padres have an advantage over the Giants in their upcoming six-game series. The Giants placed two starting pitchers, Robbie Ray and Jordan Hicks, on the 15-day IL on Tuesday. The Giants ...

  25. Frustrating Chicago White Sox Player Set For Rehab Assignment

    Yoan Moncada, the frustrating infielder for the Chicago White Sox, is finally set to begin a rehab assignment next week. ... Oft-injured, he played just 104 games in 2022 and 92 games in 2023. He ...

  26. Build Conway's Game of Life With Python

    Step 5: Implement the Game's CLI. In this section, you'll create the command-line interface (CLI) for your Game of Life project. This interface will allow your users to interact with the game and run it with different life patterns. You'll use the argparse module from the standard library to build the CLI.

  27. As Twins' free fall continues, Byron Buxton still needs to up intensity

    As the Twins continued their free fall with a 5-1 loss to the Atlanta Braves on Wednesday, the team's eighth defeat in 10 games, the intensity provided by Buxton and shortstop Carlos Correa is ...

  28. Astros Designate Former Dodgers Prospect For Assignment

    Amaya spent the majority of 2023 playing for Triple-A Jacksonville, batting .252 with 26 doubles, two triples, 15 home runs, 65 RBI, and a .752 OPS in 128 games. "It was a relief, just to hear ...

  29. Build a Tic-Tac-Toe Game Engine With an AI Player in Python

    Step 2: Scaffold a Generic Tic-Tac-Toe Game Engine. Pull the Players' Moves to Drive the Game. Let the Computer Pick a Random Move. Make an Abstract Tic-Tac-Toe Grid Renderer. Step 3: Build a Game Front End for the Console. Render the Grid With ANSI Escape Codes. Create an Interactive Console Player.

  30. Orioles designate reliever Dillon Tate for assignment

    Orioles designate reliever Dillon Tate for assignment, claim OF Forrest Wall off waivers ... Tate, 30, posted a 4.59 ERA in 29 games for the Orioles this season, his first year back on the mound ...