Top 5 Games in Python That Kids Can Make

Top 5 Games in Python That Kids Can Make

Paint

The vast majority of us know about paint application in Windows that we use to draw pictures and shading them. In any case, imagine a scenario in which you make your own paint program with Pygame. Isn’t it invigorating?

The total application can be seen in the following sub-modules: Creating a Window to draw: As an initial step, we will make a window on which we will draw. This window will be utilized to hold the photos being drawn. selecting the colors of the pencil: In request to draw multi-colored pictures, you really want the choice to pick pencils of various tones. Lastly, a code to draw a picture when the mouse is gotten across the window.

import pygame
import pygame.gfxdraw
#Initializing pygame module
pygame.init()
 
#Screen variables
screen_width = 700
screen_height =500
 
# Defining Colors
white = (255, 255, 255)
blue = (67,238,250)
red = (255, 0, 0)
black = (0, 0, 0)
green = (38,245,45)
pink = (255,192,203)
orange = (255,165,0)
yellow = (255,255,0)
violet = (177, 3, 252)
 
#Setting default color to black
pencolour = black
 
 
drawingwindow =  pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption("Paint - By Bhavik Agarwal")
drawingwindow.fill((255,255,255))
 
#Loading backgroud image and drawing it on screen
backimg = pygame.image.load("paint.png").convert_alpha()
drawingwindow.blit(backimg, (0,0))
 
#rect for the drawing area
clearrect = (119, 17, 562, 465)
 
#Defining rect value for colors in colorbox
col1= (22, 81, 30, 34)
col2= (56, 81, 34, 34)
col3= (22, 120, 30, 33)
col4= (56, 120, 34, 32)
col5= (22, 156, 30, 33)
col6= (56, 156, 34, 32)
col7= (22, 192, 30, 33)
col8= (56, 192, 34, 32)
 
#Rect that highlight which button is selected
buttonselect = (22, 81, 30, 34)
 
#Function to draw color box
def drawrectangle():    
    pygame.gfxdraw.box(drawingwindow, col1, black)
    pygame.gfxdraw.box(drawingwindow, col2, blue)
    pygame.gfxdraw.box(drawingwindow, col3, red)
    pygame.gfxdraw.box(drawingwindow, col4, green)
    pygame.gfxdraw.box(drawingwindow, col5, pink)
    pygame.gfxdraw.box(drawingwindow, col6, orange)
    pygame.gfxdraw.box(drawingwindow, col7, yellow)
    pygame.gfxdraw.box(drawingwindow, col8, violet)
drawrectangle()
 
#Set mouse cursor for pencil (default)
pygame.mouse.set_cursor(*pygame.cursors.broken_x)
exit_game = False
 
#Gameloop
while not exit_game:
    
 
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit_game = True
    
                        
        #Check for button clicks
        t = pygame.mouse.get_pressed()
        if t[0] == 1:     
            mousepos = pygame.mouse.get_pos()
            if 122 < mousepos[0] < 678 and 21 < mousepos[1] < 480:
                pygame.gfxdraw.filled_ellipse(drawingwindow,mousepos[0], mousepos[1],4,4,pencolour)
                
            elif 22 < mousepos[0] < 52 and 81 < mousepos[1] < 115:
                pencolour = black
                drawrectangle()         
                buttonselect = (22, 81, 30, 34)
                
            elif 56 < mousepos[0] < 90 and 81 < mousepos[1] < 115:
                pencolour = blue
                drawrectangle()
                buttonselect = (56, 81, 34, 34)
                
            elif 22 < mousepos[0] < 52 and 120 < mousepos[1] < 153:
                pencolour = red
                drawrectangle()
                buttonselect = (22, 120, 30, 33)
                
            elif 56 < mousepos[0] < 90 and 120 < mousepos[1] < 152:
                pencolour = green
                drawrectangle()
                buttonselect = (56, 120, 34, 32)
                
            elif 22 < mousepos[0] < 52 and 156 < mousepos[1] < 189:
                pencolour = pink
                drawrectangle()
                buttonselect = (22, 156, 30, 33)
                
            elif 56 < mousepos[0] < 90 and 156 < mousepos[1] < 188:
                pencolour = orange
                drawrectangle()
                buttonselect = (56, 156, 34, 32)
                
            elif 22 < mousepos[0] < 52 and 192 < mousepos[1] < 225:
                pencolour = yellow
                drawrectangle()
                buttonselect = (22, 192, 30, 33)
                
            elif 56 < mousepos[0] < 90 and 192 < mousepos[1] < 224:
                pencolour = violet
                drawrectangle()
                buttonselect = (56, 192, 34, 32)
            #Eraser
            elif 13 < mousepos[0] < 54 and 247 < mousepos[1] < 285:
                pencolour = white
                drawrectangle()
                pygame.mouse.set_cursor(*pygame.cursors.diamond)
            #Pencil
            elif 59 < mousepos[0] < 97 and 247 < mousepos[1] < 288:
                pencolour = black
                drawrectangle()
                pygame.mouse.set_cursor(*pygame.cursors.broken_x)
                buttonselect = (22, 81, 30, 34)
                
            elif 15 < mousepos[0] < 96 and 363 < mousepos[1] < 400:                
                pygame.gfxdraw.box(drawingwindow, clearrect, white)
 
        pygame.gfxdraw.rectangle(drawingwindow, buttonselect, white)
        pygame.display.update()
                
            
pygame.quit()

Snake Game

All of you have played the Snake Game and most certainly, you never needed to lose. As children, we as a whole adored searching for cheats to never see the “Game Over” message. In any case, as geeks, you would need to make this ‘Snake’ dance to your beats.

You can create a snake game by making the modules – Create the Screen, Create the Snake, Moving the Snake, Game Over when Snake hits the limits, Adding Food, Increasing the Length of the Snake, Displaying the Score.
Please use below code block.

import pygame
import time
import random
 
pygame.init()
 
white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)
 
dis_width = 600
dis_height = 400
 
dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('Snake Game')
 
clock = pygame.time.Clock()
 
snake_block = 10
snake_speed = 15
 
font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("comicsansms", 35)
 
 
def Your_score(score):
    value = score_font.render("Your Score: " + str(score), True, yellow)
    dis.blit(value, [0, 0])
 
 
 
def our_snake(snake_block, snake_list):
    for x in snake_list:
        pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block])
 
 
def message(msg, color):
    mesg = font_style.render(msg, True, color)
    dis.blit(mesg, [dis_width / 6, dis_height / 3])
 
 
def gameLoop():
    game_over = False
    game_close = False
 
    x1 = dis_width / 2
    y1 = dis_height / 2
 
    x1_change = 0
    y1_change = 0
 
    snake_List = []
    Length_of_snake = 1
 
    foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
    foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
 
    while not game_over:
 
        while game_close == True:
            dis.fill(blue)
            message("You Lost! Press C-Play Again or Q-Quit", red)
            Your_score(Length_of_snake - 1)
            pygame.display.update()
 
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        game_over = True
                        game_close = False
                    if event.key == pygame.K_c:
                        gameLoop()
 
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x1_change = -snake_block
                    y1_change = 0
                elif event.key == pygame.K_RIGHT:
                    x1_change = snake_block
                    y1_change = 0
                elif event.key == pygame.K_UP:
                    y1_change = -snake_block
                    x1_change = 0
                elif event.key == pygame.K_DOWN:
                    y1_change = snake_block
                    x1_change = 0
 
        if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
            game_close = True
        x1 += x1_change
        y1 += y1_change
        dis.fill(blue)
        pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block])
        snake_Head = []
        snake_Head.append(x1)
        snake_Head.append(y1)
        snake_List.append(snake_Head)
        if len(snake_List) > Length_of_snake:
            del snake_List[0]
 
        for x in snake_List[:-1]:
            if x == snake_Head:
                game_close = True
 
        our_snake(snake_block, snake_List)
        Your_score(Length_of_snake - 1)
 
        pygame.display.update()
 
        if x1 == foodx and y1 == foody:
            foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
            foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
            Length_of_snake += 1
 
        clock.tick(snake_speed)
 
    pygame.quit()
    quit()
 
 
gameLoop()

Dot Connect

Dot Connect game is the one where a player comes to an obvious conclusion to make boxes. The guidelines are notable: every player will make another line between two dabs (single-tick close to the line you wish to make). In the event that a player makes a box, he gets a point and will go once more. (Two boxes get two more points, yet just an additional one turn.) The most noteworthy score out of 81 boxes wins!

from Tkinter import *
import tkFont
 
TOL = 8
CELLSIZE = 40
OFFSET = 10
CIRCLERAD = 2
DOTOFFSET = OFFSET + CIRCLERAD
GAME_H = 400
GAME_W = 400
 
 
class Player(object):
 
    def __init__(self, name, color="black"):
        self.score = 0
        self.str = StringVar()
        self.name = name
        self.color = color
 
    def update(self):
        self.str.set(self.name + ": %d" % self.score)
 
 
 
class MyFrame(Frame):
 
    def __init__(self, master):
        Frame.__init__(self, master)
        self.GO_font = tkFont.Font(self, \
                                   name="GOFont", \
                                   family = "Times", \
                                   weight="bold", \
                                   size=36)
        self.canvas = Canvas(self, height = GAME_H, width = GAME_W)
        self.canvas.bind("", lambda e:self.click(e))
        self.canvas.grid(row=0,column=0)
 
        self.dots = [[self.canvas.create_oval(CELLSIZE*i+OFFSET, \
                                              CELLSIZE*j+OFFSET, \
                                              CELLSIZE*i+OFFSET+2*CIRCLERAD, \
                                              CELLSIZE*j+OFFSET+2*CIRCLERAD, \
                                              fill="black") \
                      for j in range(10)] for i in range(10)]
        self.lines = []
 
        self.infoframe = Frame(self)
        self.players = [Player("Player 1","blue"), Player("Player 2","red")]
        self.infoframe.players = [Label(self.infoframe, textvariable = i.str) for i in self.players]
        for i in self.infoframe.players:
            i.grid()
        
        self.turn = self.players[0]
        self.update_players()
        self.infoframe.grid(row = 0, column = 1, sticky = N)
 
        self.grid()
 
    def update_players(self):
        for i in self.players:
            i.update()
 
    def click(self, event):
        x,y = event.x, event.y
        orient = self.isclose(x,y)
 
        if orient:
            if self.line_exists(x,y, orient):
                return
            l = self.create_line(x,y, orient)
            score = self.new_box_made(l)
            if score:
                self.turn.score += score
                self.turn.update()
                self.check_game_over()
            else:
                index = self.players.index(self.turn)
                self.turn = self.players[1-index]
            self.lines.append(l)
 
    def create_line(self, x, y, orient):
        startx = CELLSIZE * ((x-OFFSET)//CELLSIZE) + DOTOFFSET
        starty = CELLSIZE * ((y-OFFSET)//CELLSIZE) + DOTOFFSET
        tmpx = (x-OFFSET)//CELLSIZE
        tmpy = (y-OFFSET)//CELLSIZE
        
        if orient == HORIZONTAL:
            endx = startx + CELLSIZE
            endy = starty
        else:
            endx = startx
            endy = starty + CELLSIZE
        #print "line drawn: %d,%d to %d,%d" % (startx,starty,endx,endy)
        return self.canvas.create_line(startx,starty,endx,endy)
        
 
    def new_box_made(self, line):
        score = 0
        x0,y0,x1,y1 = self.canvas.coords(line)
        if x0 == x1: # vertical line
            midx = x0
            midy = (y0+y1)/2
            pre = (x0 - CELLSIZE/2, midy)
            post = (x0 + CELLSIZE/2, midy)
        elif y0 == y1: # horizontal line
            midx = (x0 + x1)/2
            midy = y0
            pre = (midx, y0 - CELLSIZE/2)
            post = (midx, y0 + CELLSIZE/2)
        
        if len(self.find_lines(pre)) == 3:  # not 4, because newly created line is 
            self.fill_in(pre)               # is not returned (?!)
            score += 1
        if len(self.find_lines(post)) == 3:
            self.fill_in(post)
            score += 1
        return score
 
    def find_lines(self, coords):
        x, y = coords
        if x < 0 or x > GAME_W:
            return []
        if y < 0 or y > GAME_W:
            return []
        #print "Cell center: %d,%d" % (x,y)
        lines = [x for x in self.canvas.find_enclosed(x-CELLSIZE,\
                                                      y-CELLSIZE,\
                                                      x+CELLSIZE,\
                                                      y+CELLSIZE)\
                 if x in self.lines]
        #print lines
        return lines
 
    def fill_in(self, coords):
        x,y = coords
        self.canvas.create_text(x,y,text=self.turn.name, fill=self.turn.color)
        
    def isclose(self, x, y):
        x -= OFFSET
        y -= OFFSET
        dx = x - (x//CELLSIZE)*CELLSIZE
        dy = y - (y//CELLSIZE)*CELLSIZE
        
        if abs(dx) < TOL:
            if abs(dy) < TOL:
                return None  # mouse in corner of box; ignore
            else:
                return VERTICAL
        elif abs(dy) < TOL:
            return HORIZONTAL
        else:
            return None
 
    def line_exists(self, x,y, orient):
        id_ = self.canvas.find_closest(x,y,halo=TOL)[0]
        if id_ in self.lines:
            return True
        else:
            return False
 
    def check_game_over(self):
        total = sum([x.score for x in self.players])
        if total == 81:
            self.canvas.create_text(GAME_W/2, GAME_H/2, \
                                    text="GAME OVER", font="GOFont", \
                                    fill="#888")
        
        
mainw = Tk()
mainw.f = MyFrame(mainw)
mainw.mainloop()

Ping Pong

Pong is one of the most popular arcade games, reproducing table tennis. Every player controls an oar in the game by dragging it in an upward direction across the screen’s left or right side. Players use their oars to strike to and fro ready.

Turtle is an inbuilt realistic module in Python. It utilizes a board and pen to portray delineations.

The following are the stages utilized:

Stage 1) Create two oars A and B on the left and right sides of the screen.
Stage 2) Create a ball.
Stage 3) Create an occasion to move the oar in an upward direction by pressing a specific key.
Stage 4) Create the function to refresh the score after every player misses an impact.

# Import required library
import turtle
 
 
# Create screen
sc = turtle.Screen()
sc.title("Pong game")
sc.bgcolor("white")
sc.setup(width=1000, height=600)
 
 
# Left paddle
left_pad = turtle.Turtle()
left_pad.speed(0)
left_pad.shape("square")
left_pad.color("black")
left_pad.shapesize(stretch_wid=6, stretch_len=2)
left_pad.penup()
left_pad.goto(-400, 0)
 
 
# Right paddle
right_pad = turtle.Turtle()
right_pad.speed(0)
right_pad.shape("square")
right_pad.color("black")
right_pad.shapesize(stretch_wid=6, stretch_len=2)
right_pad.penup()
right_pad.goto(400, 0)
 
 
# Ball of circle shape
hit_ball = turtle.Turtle()
hit_ball.speed(40)
hit_ball.shape("circle")
hit_ball.color("blue")
hit_ball.penup()
hit_ball.goto(0, 0)
hit_ball.dx = 5
hit_ball.dy = -5
 
 
# Initialize the score
left_player = 0
right_player = 0
 
 
# Displays the score
sketch = turtle.Turtle()
sketch.speed(0)
sketch.color("blue")
sketch.penup()
sketch.hideturtle()
sketch.goto(0, 260)
sketch.write("Left_player : 0 Right_player: 0",
			align="center", font=("Courier", 24, "normal"))
 
 
# Functions to move paddle vertically
def paddleaup():
	y = left_pad.ycor()
	y += 20
	left_pad.sety(y)
 
 
def paddleadown():
	y = left_pad.ycor()
	y -= 20
	left_pad.sety(y)
 
 
def paddlebup():
	y = right_pad.ycor()
	y += 20
	right_pad.sety(y)
 
 
def paddlebdown():
	y = right_pad.ycor()
	y -= 20
	right_pad.sety(y)
 
 
# Keyboard bindings
sc.listen()
sc.onkeypress(paddleaup, "e")
sc.onkeypress(paddleadown, "x")
sc.onkeypress(paddlebup, "Up")
sc.onkeypress(paddlebdown, "Down")
 
 
while True:
	sc.update()
 
	hit_ball.setx(hit_ball.xcor()+hit_ball.dx)
	hit_ball.sety(hit_ball.ycor()+hit_ball.dy)
 
	# Checking borders
	if hit_ball.ycor() > 280:
		hit_ball.sety(280)
		hit_ball.dy *= -1
 
	if hit_ball.ycor() < -280:
		hit_ball.sety(-280)
		hit_ball.dy *= -1
 
	if hit_ball.xcor() > 500:
		hit_ball.goto(0, 0)
		hit_ball.dy *= -1
		left_player += 1
		sketch.clear()
		sketch.write("Left_player : {} Right_player: {}".format(
					left_player, right_player), align="center",
					font=("Courier", 24, "normal"))
 
	if hit_ball.xcor() < -500:
		hit_ball.goto(0, 0)
		hit_ball.dy *= -1
		right_player += 1
		sketch.clear()
		sketch.write("Left_player : {} Right_player: {}".format(
								left_player, right_player), align="center",
								font=("Courier", 24, "normal"))
 
	# Paddle ball collision
	if (hit_ball.xcor() > 360 and
						hit_ball.xcor() < 370) and
						(hit_ball.ycor() < right_pad.ycor()+40 and
						hit_ball.ycor() > right_pad.ycor()-40):
		hit_ball.setx(360)
		hit_ball.dx*=-1
		
	if (hit_ball.xcor()<-360 and
					hit_ball.xcor()>-370) and
					(hit_ball.ycor()<left_pad.ycor()+40 and
						hit_ball.ycor()>left_pad.ycor()-40):
		hit_ball.setx(-360)
		hit_ball.dx*=-1

Tic Tac Toe

Tic Tac Toe is perhaps the most played game and is the best time executioner game that you can play anyplace with simply a pen and paper. On the off chance that you don’t have the foggiest idea how to play this game don’t stress let us initially get that.

The game is played by two people. In the first place, we draw a board with a 3×3 square framework. The principal player picks ‘X’ and draws it on any of the square lattice, then, at that point, it’s the shot at the second player to draw ‘O’ on the accessible spaces. Like this, the players draw ‘X’ and ‘O’ then again on the unfilled spaces until a player prevails with regards to drawing 3 back to back marks either in the flat, vertical or inclining way. Then, at that point, the player dominates the match in any case the game draws when all spots are filled.

# Tic-Tac-Toe Program using
# random number in Python

# importing all necessary libraries
import numpy as np
import random
from time import sleep

# Creates an empty board
def create_board():
	return(np.array([[0, 0, 0],
					[0, 0, 0],
					[0, 0, 0]]))

# Check for empty places on board
def possibilities(board):
	l = []
	
	for i in range(len(board)):
		for j in range(len(board)):
			
			if board[i][j] == 0:
				l.append((i, j))
	return(l)

# Select a random place for the player
def random_place(board, player):
	selection = possibilities(board)
	current_loc = random.choice(selection)
	board[current_loc] = player
	return(board)

# Checks whether the player has three
# of their marks in a horizontal row
def row_win(board, player):
	for x in range(len(board)):
		win = True
		
		for y in range(len(board)):
			if board[x, y] != player:
				win = False
				continue
				
		if win == True:
			return(win)
	return(win)

# Checks whether the player has three
# of their marks in a vertical row
def col_win(board, player):
	for x in range(len(board)):
		win = True
		
		for y in range(len(board)):
			if board[y][x] != player:
				win = False
				continue
				
		if win == True:
			return(win)
	return(win)

# Checks whether the player has three
# of their marks in a diagonal row
def diag_win(board, player):
	win = True
	y = 0
	for x in range(len(board)):
		if board[x, x] != player:
			win = False
	if win:
		return win
	win = True
	if win:
		for x in range(len(board)):
			y = len(board) - 1 - x
			if board[x, y] != player:
				win = False
	return win

# Evaluates whether there is
# a winner or a tie
def evaluate(board):
	winner = 0
	
	for player in [1, 2]:
		if (row_win(board, player) or
			col_win(board,player) or
			diag_win(board,player)):
				
			winner = player
			
	if np.all(board != 0) and winner == 0:
		winner = -1
	return winner

# Main function to start the game
def play_game():
	board, winner, counter = create_board(), 0, 1
	print(board)
	sleep(2)
	
	while winner == 0:
		for player in [1, 2]:
			board = random_place(board, player)
			print("Board after " + str(counter) + " move")
			print(board)
			sleep(2)
			counter += 1
			winner = evaluate(board)
			if winner != 0:
				break
	return(winner)

# Driver Code
print("Winner is: " + str(play_game()))

Conclusion

We have given 5 fun activities or game those you can create by yourselves using python. you just need a text editor to do the coding and game will be ready to play. if you want know know more about learning python for kids and reference books then please go through the article
have fun and happy learning 🙂

Encourage Your Kids to Code: A Parent-Friendly Guide to Python Programming.

Python for Kids: A Playful Introduction to Programming.

The Python Champions of Coding: A Complete Book of Programming for Beginners and Kids

Computer Coding Python Games for Kids

1 thought on “Top 5 Games in Python That Kids Can Make”

  1. Pingback: python programming language for kids -

Comments are closed.