How to Guess Again in Python

Today we're going to learn how to lawmaking some easy games in Python using a few mutual Python modules.

Why are we using Python?

Python is a well-known programming language. Python is very easy to understand and code. It is believed to exist developer-friendly. Whatsoever beginner tin can learn to code in python within a brusque span of time.

Some of nigh interesting features of this language are equally follows :

  • Python is open source and gratuitous
  • Portable and dynamic
  • Super piece of cake to understand etc.

Creating Easy Games in Python

Allow'south now implement some easy games in Python that yous can build as a beginner to get a headstart in your learning curve!

i. A Quiz Game in Python

This is a very unproblematic text-based game in python. It a small quiz which you can make for yourself too or your friends. We do not need to import whatsoever modules for this game which makes it easier! Effort it yourself 😉

Hither are employ:

  • if-else statement – For checking answers
  • Print statement – for printing outputs
print('Welcome to AskPython Quiz') answer=input('Are you set up to play the Quiz ? (aye/no) :') score=0 total_questions=3  if respond.lower()=='yes':     answer=input('Question 1: What is your Favourite programming language?')     if respond.lower()=='python':         score += 1         print('correct')     else:         impress('Incorrect Reply :(')       respond=input('Question 2: Do you follow whatsoever author on AskPython? ')     if answer.lower()=='yes':         score += ane         print('correct')     else:         print('Wrong Answer :(')      respond=input('Question 3: What is the name of your favourite website for learning Python?')     if answer.lower()=='askpython':         score += 1         print('correct')     else:         print('Wrong Answer :(')  print('Thankyou for Playing this modest quiz game, you attempted',score,"questions correctly!") mark=(score/total_questions)*100 impress('Marks obtained:',marking) print('BYE!')                

Output:

Welcome to AskPython Quiz Are y'all ready to play the Quiz ? (yeah/no) :yes Question 1: What is your Favourite programming linguistic communication?python correct Question 2: Do you follow whatsoever writer on AskPython? aye correct Question 3: What is the proper noun of your favourite website for learning Python?askpython correct Thankyou for Playing this small quiz game, you attempted 3 questions correctly! Marks obtained: 100.0 BYE!                

2. Pong Game in Python

Most of us accept heard well-nigh the famous pong game. Many of us love playing it. Today lets larn how to lawmaking this archetype game using the python programming language!

Before starting with the coding office nosotros beginning need to install the turtle module. The turtle module is a Python library that enables users to create pictures and shapes past providing them with a virtual canvas.

If you don't already have information technology, you can install the library using pip.

C:\Users\Admin>pip install turtle                

Read more than about the turtle library in their official documentation.

Endeavor the code yourself!

import turtle as t playerAscore=0 playerBscore=0  #create a window and declare a variable called window and call the screen() window=t.Screen() window.title("The Pong Game") window.bgcolor("green") window.setup(width=800,peak=600) window.tracer(0)  #Creating the left paddle leftpaddle=t.Turtle() leftpaddle.speed(0) leftpaddle.shape("square") leftpaddle.color("white") leftpaddle.shapesize(stretch_wid=5,stretch_len=1) leftpaddle.penup() leftpaddle.goto(-350,0)  #Creating the right paddle rightpaddle=t.Turtle() rightpaddle.speed(0) rightpaddle.shape("square") rightpaddle.color("white") rightpaddle.shapesize(stretch_wid=v,stretch_len=1) rightpaddle.penup() rightpaddle.goto(-350,0)  #Lawmaking for creating the ball brawl=t.Turtle() ball.speed(0) ball.shape("circle") ball.color("red") brawl.penup() brawl.goto(v,five) ballxdirection=0.2 ballydirection=0.2  #Code for creating pen for scorecard update pen=t.Turtle() pen.speed(0) pen.colour("Bluish") pen.penup() pen.hideturtle() pen.goto(0,260) pen.write("score",align="middle",font=('Arial',24,'normal'))  #lawmaking for moving the leftpaddle def leftpaddleup():     y=leftpaddle.ycor()     y=y+90     leftpaddle.sety(y)  def leftpaddledown():     y=leftpaddle.ycor()     y=y+90     leftpaddle.sety(y)  #lawmaking for moving the rightpaddle def rightpaddleup():     y=rightpaddle.ycor()     y=y+xc     rightpaddle.sety(y)  def rightpaddledown():     y=rightpaddle.ycor()     y=y+90     rightpaddle.sety(y)  #Assign keys to play window.listen() window.onkeypress(leftpaddleup,'w') window.onkeypress(leftpaddledown,'southward') window.onkeypress(rightpaddleup,'Upwards') window.onkeypress(rightpaddledown,'Downwardly')  while True:     window.update()      #moving the ball     ball.setx(ball.xcor()+ballxdirection)     brawl.sety(ball.ycor()+ballxdirection)      #border set     if ball.ycor()>290:         brawl.sety(290)         ballydirection=ballydirection*-i     if ball.ycor()<-290:         ball.sety(-290)         ballydirection=ballydirection*-i              if brawl.xcor() > 390:         ball.goto(0,0)         ball_dx = ball_dx * -1         player_a_score = player_a_score + ane         pen.articulate()         pen.write("Role player A: {}                    Thespian B: {} ".format(player_a_score,player_b_score),align="centre",font=('Monaco',24,"normal"))         os.system("afplay wallhit.wav&")        if(ball.xcor()) < -390: # Left width paddle Border         brawl.goto(0,0)         ball_dx = ball_dx * -one         player_b_score = player_b_score + 1         pen.clear()         pen.write("Histrion A: {}                    Player B: {} ".format(player_a_score,player_b_score),align="center",font=('Monaco',24,"normal"))         os.system("afplay wallhit.wav&")       # Handling the collisions with paddles.      if(brawl.xcor() > 340) and (brawl.xcor() < 350) and (ball.ycor() < paddle_right.ycor() + 40 and ball.ycor() > paddle_right.ycor() - 40):         ball.setx(340)         ball_dx = ball_dx * -ane         os.arrangement("afplay paddle.wav&")      if(brawl.xcor() < -340) and (ball.xcor() > -350) and (ball.ycor() < paddle_left.ycor() + 40 and ball.ycor() > paddle_left.ycor() - 40):         ball.setx(-340)         ball_dx = ball_dx * -one         os.system("afplay paddle.wav&")                

Output:

Pong - easy games in Python
Pong Game

three. Hungry Snake Game in Python

This was most of us favourite game when we were kids. We can actually code this game in python by importing only ii modules! How cool is that!

Let'south get started!

Firstly, nosotros need to install turtle. If you lot don't have information technology already installed, open up your cmd and type in the post-obit command.

C:\Users\Admin>pip install turtle                

Now nosotros will install the random module. The random module is used to generate random numbers. In your cmd type in the following control.

C:\Users\Admin>pip install random2                

Code and Try it yourself and enjoy the game!

import turtle import random  w = 500 h = 500 food_size = 10 delay = 100   offsets = {     "up": (0, xx),     "down": (0, -20),     "left": (-20, 0),     "correct": (20, 0) }  def reset():     global snake, snake_dir, food_position, pen     snake = [[0, 0], [0, xx], [0, twoscore], [0, 60], [0, 80]]     snake_dir = "upwardly"     food_position = get_random_food_position()     nutrient.goto(food_position)     move_snake()      def move_snake():     global snake_dir      new_head = snake[-i].copy()     new_head[0] = ophidian[-one][0] + offsets[snake_dir][0]     new_head[one] = snake[-i][1] + offsets[snake_dir][1]           if new_head in ophidian[:-1]:         reset()     else:         ophidian.append(new_head)               if non food_collision():             snake.pop(0)           if serpent[-1][0] > due west / 2:             snake[-1][0] -= w         elif snake[-1][0] < - w / 2:             snake[-1][0] += due west         elif snake[-1][one] > h / 2:             serpent[-1][1] -= h         elif ophidian[-1][1] < -h / 2:             snake[-one][ane] += h           pen.clearstamps()                   for segment in snake:             pen.goto(segment[0], segment[1])             pen.postage()                   screen.update()          turtle.ontimer(move_snake, delay)  def food_collision():     global food_position     if get_distance(snake[-1], food_position) < twenty:         food_position = get_random_food_position()         food.goto(food_position)         return True     render Simulated  def get_random_food_position():     x = random.randint(- westward / 2 + food_size, w / two - food_size)     y = random.randint(- h / two + food_size, h / ii - food_size)     return (10, y)  def get_distance(pos1, pos2):     x1, y1 = pos1     x2, y2 = pos2     altitude = ((y2 - y1) ** 2 + (x2 - x1) ** ii) ** 0.5     render distance def go_up():     global snake_dir     if snake_dir != "downwardly":         snake_dir = "up"  def go_right():     global snake_dir     if snake_dir != "left":         snake_dir = "correct"  def go_down():     global snake_dir     if snake_dir!= "up":         snake_dir = "down"  def go_left():     global snake_dir     if snake_dir != "correct":         snake_dir = "left"   screen = turtle.Screen() screen.setup(westward, h) screen.title("Serpent") screen.bgcolor("bluish") screen.setup(500, 500) screen.tracer(0)   pen = turtle.Turtle("square") pen.penup()   food = turtle.Turtle() food.shape("foursquare") food.colour("yellow") food.shapesize(food_size / 20) food.penup()   screen.listen() screen.onkey(go_up, "Up") screen.onkey(go_right, "Correct") screen.onkey(go_down, "Down") screen.onkey(go_left, "Left")   reset() turtle.done()                

Output:

Snake - easy games in Python

Determination

And that's it! These are some of the like shooting fish in a barrel games in Python that y'all tin create equally a beginner and accept some fun! We loved edifice these projects and nosotros hope you practice too!

holimanbracken.blogspot.com

Source: https://www.askpython.com/python/examples/easy-games-in-python

0 Response to "How to Guess Again in Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel