Hướng dẫn python game code for beginners - mã trò chơi python cho người mới bắt đầu

Hôm nay, chúng tôi sẽ học cách viết mã một số trò chơi dễ dàng trong Python bằng một vài mô -đun Python phổ biến.

Tại sao chúng ta sử dụng Python?

Python là một ngôn ngữ lập trình nổi tiếng. Python rất dễ hiểu và mã. Nó được cho là thân thiện với nhà phát triển. Bất kỳ người mới bắt đầu nào cũng có thể học cách viết mã trong Python trong một khoảng thời gian ngắn.

Một số tính năng thú vị nhất của ngôn ngữ này như sau:

  • Python là nguồn mở và miễn phí
  • Di động và năng động
  • Siêu dễ hiểu, v.v.

Tạo các trò chơi dễ dàng trong Python

Bây giờ, hãy thực hiện một số trò chơi dễ dàng trong Python mà bạn có thể xây dựng như một người mới bắt đầu để có được một đầu trong đường cong học tập của bạn!

1. Một trò chơi đố trong Python

Đây là một trò chơi dựa trên văn bản rất đơn giản trong Python. Đó là một câu đố nhỏ mà bạn cũng có thể tự làm hoặc bạn bè của bạn. Chúng tôi không cần nhập bất kỳ mô -đun nào cho trò chơi này giúp nó dễ dàng hơn! Tự mình thử 😉

Đây là sử dụng:

  • Tuyên bố IF-Else-để kiểm tra câu trả lời
  • Tuyên bố in - để in đầu ra

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!')

Output:

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. Trò chơi Pong trong Python

Hầu hết chúng ta đã nghe nói về trò chơi Pong nổi tiếng. Nhiều người trong chúng ta thích chơi nó. Hôm nay hãy tìm hiểu cách viết mã trò chơi cổ điển này bằng ngôn ngữ lập trình Python!

Trước khi bắt đầu với phần mã hóa, trước tiên chúng tôi cần cài đặt mô -đun rùa. Mô -đun rùa & nbsp; là thư viện A & NBSP; Python & NBSP; cho phép người dùng tạo hình ảnh và hình dạng bằng cách cung cấp cho chúng một bức tranh ảo.turtle module is a Python library that enables users to create pictures and shapes by providing them with a virtual canvas.

Nếu bạn không có nó, bạn có thể cài đặt thư viện bằng PIP.

C:\Users\Admin>pip install turtle

Đọc thêm về Thư viện Rùa trong tài liệu chính thức của họ.

Hãy tự mình thử mã!

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()<-290:
        ball.sety(-290)
        ballydirection=ballydirection*-1
         
    if ball.xcor() > 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&")

Output:

Hướng dẫn python game code for beginners - mã trò chơi python cho người mới bắt đầu
Trò chơi Pong


3. Trò chơi rắn đói ở Python

Đây là hầu hết các trò chơi yêu thích của chúng tôi khi chúng tôi còn là những đứa trẻ. Chúng ta thực sự có thể mã hóa trò chơi này trong Python bằng cách nhập chỉ hai mô -đun! Thật tuyệt làm sao!

Bắt đầu nào!

Thứ nhất, chúng ta cần lắp đặt rùa. Nếu bạn không có nó đã được cài đặt, hãy mở CMD của bạn và nhập lệnh sau.

C:\Users\Admin>pip install turtle

Bây giờ chúng tôi sẽ cài đặt mô -đun ngẫu nhiên. Mô -đun ngẫu nhiên được sử dụng để tạo số ngẫu nhiên. Trong loại CMD của bạn trong lệnh sau.

C:\Users\Admin>pip install random2

Mã và tự mình thử và thưởng thức trò chơi!

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()

Output:

Hướng dẫn python game code for beginners - mã trò chơi python cho người mới bắt đầu

Sự kết luận

Và đó là nó! Đây là một số trò chơi dễ dàng trong Python mà bạn có thể tạo như một người mới bắt đầu và có một số niềm vui! Chúng tôi thích xây dựng các dự án này và chúng tôi hy vọng bạn cũng vậy!

Làm thế nào để bạn tạo ra một trò chơi Python đơn giản cho người mới bắt đầu?

Bước 1: Xin chào Bunny..
Nhập thư viện pygame. ....
Khởi tạo pygame và thiết lập cửa sổ hiển thị ..
Tải hình ảnh mà bạn sẽ sử dụng cho chú thỏ ..
Tiếp tục lặp qua mã thụt lề sau. ....
Đổ đầy màn hình với màu đen trước khi bạn vẽ bất cứ thứ gì ..
Thêm hình ảnh thỏ mà bạn đã tải vào màn hình tại x = 100 và y = 100 ..

Bạn có thể tạo một trò chơi với mã Python không?

Tạo các trò chơi máy tính của riêng bạn trong Python là một cách tuyệt vời để học ngôn ngữ.Để xây dựng một trò chơi, bạn sẽ cần sử dụng nhiều kỹ năng lập trình cốt lõi.Các loại kỹ năng mà bạn sẽ thấy trong lập trình trong thế giới thực.. 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.

Trò chơi Python dễ dàng nhất để thực hiện là gì?

Các dự án Python bạn có thể xây dựng..
Điên cuồng ..
Đoán trò chơi số (máy tính).
Đoán trò chơi số (người dùng).
Oẳn tù tì..
Hangman..
Đếm thời gian đếm ngược ..
Tạo mật khẩu..
Bộ mã hóa / bộ giải mã mã QR ..

Người mới bắt đầu sử dụng mã nào cho Python?

Ý tưởng dự án Python: Cấp độ mới bắt đầu..
Tạo một trình tạo mã.....
Xây dựng một máy tính đếm ngược.....
Viết một phương thức sắp xếp.....
Xây dựng một bài kiểm tra tương tác.....
Tic-tac-toe theo văn bản.....
Tạo một bộ chuyển đổi nhiệt độ/đo lường.....
Xây dựng một ứng dụng quầy.....
Xây dựng một trò chơi đoán số ..