Can you code games in python

Easy Games in Python

game

Today we’re going to learn how to code some easy games in Python using a few common 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 be developer-friendly. Any beginner can learn to code in python within a short span of time.

Some of most interesting features of this language are as follows :

  • Python is open source and free
  • Portable and dynamic
  • Super easy to understand etc.

Creating Easy Games in Python

Let’s now implement some easy games in Python that you can build as a beginner to get a headstart in your learning curve!

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 😉

print('Welcome to AskPython Quiz') answer=input('Are you ready to play the Quiz ? (yes/no) :') score=0 total_questions=3 if answer.lower()=='yes': answer=input('Question 1: What is your Favourite programming language?') if answer.lower()=='python': score += 1 print('correct') else: print('Wrong Answer :(') answer=input('Question 2: Do you follow any author on AskPython? ') if answer.lower()=='yes': score += 1 print('correct') else: print('Wrong Answer :(') answer=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 small quiz game, you attempted',score,"questions correctly!") mark=(score/total_questions)*100 print('Marks obtained:',mark) print('BYE!')
Welcome to AskPython Quiz Are you ready to play the Quiz ? (yes/no) :yes Question 1: What is your Favourite programming language?python correct Question 2: Do you follow any author on AskPython? yes correct Question 3: What is the name 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 have heard about the famous pong game. Many of us love playing it. Today lets learn how to code this classic game using the python programming language!

Before starting with the coding part we first need to install the turtle module. The turtle module is a Python library that enables users to create pictures and shapes by providing them with a virtual canvas.

If you don’t already have it, you can install the library using pip.

C:\Users\Admin>pip install turtle

Read more about the turtle library in their official documentation.

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,height=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=5,stretch_len=1) rightpaddle.penup() rightpaddle.goto(-350,0) #Code for creating the ball ball=t.Turtle() ball.speed(0) ball.shape("circle") ball.color("red") ball.penup() ball.goto(5,5) ballxdirection=0.2 ballydirection=0.2 #Code for creating pen for scorecard update pen=t.Turtle() pen.speed(0) pen.color("Blue") pen.penup() pen.hideturtle() pen.goto(0,260) pen.write("score",align="center",font=('Arial',24,'normal')) #code 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) #code for moving the rightpaddle def rightpaddleup(): y=rightpaddle.ycor() y=y+90 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,'s') window.onkeypress(rightpaddleup,'Up') window.onkeypress(rightpaddledown,'Down') while True: window.update() #moving the ball ball.setx(ball.xcor()+ballxdirection) ball.sety(ball.ycor()+ballxdirection) #border set up if ball.ycor()>290: ball.sety(290) ballydirection=ballydirection*-1 if ball.ycor() 390: ball.goto(0,0) ball_dx = ball_dx * -1 player_a_score = player_a_score + 1 pen.clear() pen.write("Player A: <> Player B: <> ".format(player_a_score,player_b_score),align="center",font=('Monaco',24,"normal")) os.system("afplay wallhit.wav&") if(ball.xcor()) < -390: # Left width paddle Border ball.goto(0,0) ball_dx = ball_dx * -1 player_b_score = player_b_score + 1 pen.clear() pen.write("Player 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(ball.xcor() > 340) and (ball.xcor() < 350) and (ball.ycor() < rightpaddle.ycor() + 40 and ball.ycor() >rightpaddle.ycor() - 40): ball.setx(340) ball_dx = ball_dx * -1 os.system("afplay paddle.wav&") if(ball.xcor() < -340) and (ball.xcor() >-350) and (ball.ycor() < leftpaddle.ycor() + 40 and ball.ycor() >leftpaddle.ycor() - 40): ball.setx(-340) ball_dx = ball_dx * -1 os.system("afplay paddle.wav&")

Pong - easy games in Python

3. Hungry Snake Game in Python

This was most of our favorite game when we were kids. We can actually code this game in python by importing just two modules! How cool is that!

Читайте также:  Установка pip3 python 3

Firstly, we need to install turtle. If you don’t have it already installed, open your cmd and type in the following command.

C:\Users\Admin>pip install turtle

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

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, 20), "down": (0, -20), "left": (-20, 0), "right": (20, 0) >def reset(): global snake, snake_dir, food_position, pen snake = [[0, 0], [0, 20], [0, 40], [0, 60], [0, 80]] snake_dir = "up" food_position = get_random_food_position() food.goto(food_position) move_snake() def move_snake(): global snake_dir new_head = snake[-1].copy() new_head[0] = snake[-1][0] + offsets[snake_dir][0] new_head[1] = snake[-1][1] + offsets[snake_dir][1] if new_head in snake[:-1]: reset() else: snake.append(new_head) if not food_collision(): snake.pop(0) if snake[-1][0] > w / 2: snake[-1][0] -= w elif snake[-1][0] < - w / 2: snake[-1][0] += w elif snake[-1][1] >h / 2: snake[-1][1] -= h elif snake[-1][1] < -h / 2: snake[-1][1] += h pen.clearstamps() for segment in snake: pen.goto(segment[0], segment[1]) pen.stamp() screen.update() turtle.ontimer(move_snake, delay) def food_collision(): global food_position if get_distance(snake[-1], food_position) < 20: food_position = get_random_food_position() food.goto(food_position) return True return False def get_random_food_position(): x = random.randint(- w / 2 + food_size, w / 2 - food_size) y = random.randint(- h / 2 + food_size, h / 2 - food_size) return (x, y) def get_distance(pos1, pos2): x1, y1 = pos1 x2, y2 = pos2 distance = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5 return distance def go_up(): global snake_dir if snake_dir != "down": snake_dir = "up" def go_right(): global snake_dir if snake_dir != "left": snake_dir = "right" def go_down(): global snake_dir if snake_dir!= "up": snake_dir = "down" def go_left(): global snake_dir if snake_dir != "right": snake_dir = "left" screen = turtle.Screen() screen.setup(w, h) screen.title("Snake") screen.bgcolor("blue") screen.setup(500, 500) screen.tracer(0) pen = turtle.Turtle("square") pen.penup() food = turtle.Turtle() food.shape("square") food.color("yellow") food.shapesize(food_size / 20) food.penup() screen.listen() screen.onkey(go_up, "Up") screen.onkey(go_right, "Right") screen.onkey(go_down, "Down") screen.onkey(go_left, "Left") reset() turtle.done()

Snake - easy games in Python

Conclusion

And that’s it! These are some of the easy games in Python that you can create as a beginner and have some fun! We loved building these projects and we hope you do too!

Читайте также:  Display details in html

Источник

Пишем простую игру на python

Первое, что нам нужно, это начальная структура, окошко, у меня оно будет выглядеть так:

from tkinter import * import random as rdm class Main(Frame): def __init__(self, root): super(Main, self).__init__(root) self.startUI() def startUI(self): pass if __name__ == '__main__': root = Tk() root.geometry("500x500+200+200") root.title("Камень, ножницы, бумага") root.resizable(False, False) root["bg"] = "#FFF" app = Main(root) app.pack() root.mainloop() 

Здесь мы создаём неизменяемое окно 500 на 500 с заголовком «Камень, ножницы, бумага» и белым фоном. Именно в это окошко мы будем добавлять кнопочки, счетчики и т.д.

Теперь в наш метод startUI добавим такие строчки:

btn = Button(root, text="Камень", font=("Times New Roman", 15)) btn = Button(root, text="Ножницы", font=("Times New Roman", 15)) btn3 = Button(root, text="Бумага", font=("Times New Roman", 15)) btn.place(x=10, y=100, width=120, height=50) btn2.place(x=155, y=100, width=120, height=50) btn3.place(x=300, y=100, width=120, height=50) 

Эти 7 строчек добавят в наше окно 3 кнопки которые нечего не делают. Мы исправим это позже.

Пользователь делает свой выбор, нажимая на одну из 3 кнопок, это круто, но нам нужен оппонент, именно для этого нужен модуль random.

А вот теперь мы добавим функцию, которая будет обрабатывать выбор, и выдавать ответ, кто же выиграл в этом раунде. Сделаем это вот таким образом:

btn = Button(root, text="Камень", font=("Times New Roman", 15), command=lambda x=1: self.btn_click(x)) btn2 = Button(root, text="Ножницы", font=("Times New Roman", 15), command=lambda x=2: self.btn_click(x)) btn3 = Button(root, text="Бумага", font=("Times New Roman", 15), command=lambda x=3: self.btn_click(x)) 

Всё очень просто. Грубо говоря, если игрок нажмет камень, отправится 1, если ножницы, то 2, а если бумага, то 3, причем не только отправится, но и выведется в консоль.
На счет компьютера. Он свой выбор делает, но его выбор никуда не идёт.

Читайте также:  Кнопка button html css

Перед тем, как делать логику, нам нужно передать игроку результат, и для этого мы будем использовать Label. Добавим в startUI такие строчки:

self.lbl = Label(root, text="Начало игры!", bg="#FFF", font=("Times New Roman", 21, "bold")) self.lbl.place(x=120, y=25) self.lbl2 = Label(root, justify="left", font=("Times New Roman", 13), text=f"Побед: \nПроигрышей:" f" \nНичей: ", bg="#FFF") self.lbl2.place(x=5, y=5) 

Отлично. Теперь у нас есть надпись, в которую мы будем выводить результат раунда и надпись со статистикой.

1. Поражений
2. Побед
3. Ничей

Для этого все в тот же startUI добавим такую строку:

self.win = self.drow = self.lose = 0 

Теперь в классе main создаем метод btn_click, и пишем в него следующие строки:

def btn_click(self, choise): comp_choise = rdm.randint(1, 3) print(choise) 

Недолго музыка играла. Там же, в btn_click, удаляем

if choise == comp_choise: self.drow += 1 self.lbl.configure(text="Ничья") elif choise == 1 and comp_choise == 2 \ or choise == 2 and comp_choise == 3 \ or choise == 3 and comp_choise == 1: self.win += 1 self.lbl.configure(text="Победа") else: self.lose += 1 self.lbl.configure(text="Проигрыш") self.lbl2.configure(text=f"Побед: \nПроигрышей:" f" \nНичей: ") del comp_choise 

Собственно всё, на этом создание закончилось. Всё работает, можно играть.

Полный код:

from tkinter import * import random as rdm class Main(Frame): def __init__(self, root): super(Main, self).__init__(root) self.startUI() def startUI(self): btn = Button(root, text="Камень", font=("Times New Roman", 15), command=lambda x=1: self.btn_click(x)) btn2 = Button(root, text="Ножницы", font=("Times New Roman", 15), command=lambda x=2: self.btn_click(x)) btn3 = Button(root, text="Бумага", font=("Times New Roman", 15), command=lambda x=3: self.btn_click(x)) btn.place(x=10, y=100, width=120, height=50) btn2.place(x=155, y=100, width=120, height=50) btn3.place(x=300, y=100, width=120, height=50) self.lbl = Label(root, text="Начало игры!", bg="#FFF", font=("Times New Roman", 21, "bold")) self.lbl.place(x=150, y=25) self.win = self.drow = self.lose = 0 self.lbl2 = Label(root, justify="left", font=("Times New Roman", 13), text=f"Побед: \nПроигрышей:" f" \nНичей: ", bg="#FFF") self.lbl2.place(x=5, y=5) def btn_click(self, choise): comp_choise = rdm.randint(1, 3) if choise == comp_choise: self.drow += 1 self.lbl.configure(text="Ничья") elif choise == 1 and comp_choise == 2 \ or choise == 2 and comp_choise == 3 \ or choise == 3 and comp_choise == 1: self.win += 1 self.lbl.configure(text="Победа") else: self.lose += 1 self.lbl.configure(text="Проигрыш") self.lbl2.configure(text=f"Побед: \nПроигрышей:" f" \nНичей: ") del comp_choise if __name__ == '__main__': root = Tk() root.geometry("430x160+200+200") root.title("Камень, ножницы, бумага") root.resizable(False, False) root["bg"] = "#FFF" app = Main(root) app.pack() root.mainloop() 

Источник

Оцените статью