如何使用Python编写简单的游戏?

14天阅读挑战赛

如何使用Python编写简单的游戏?_第1张图片 

今天,我们将学习如何使用几个常见的Python模块在Python中编写一些简单的游戏。

我们为什么要使用Python?

Python是一种著名的编程语言。Python非常易于理解和编写代码。它被认为是对开发人员友好的。任何初学者都可以在短时间内学会用python编写代码。

Python语言的一些最有趣的特性如下:

-Python是开源和免费的

-便携式和动态

-超级容易理解等。

Python创建简单游戏

现在,让我们用Python实现一些简单的游戏,您可以作为初学者构建这些游戏,以在学习曲线中取得领先!

1.Python中的测验游戏

这是一个非常简单的python文本游戏。这是一个小测验,你也可以为自己或朋友做。我们不需要为这个游戏导入任何模块,这使它更容易!你自己试试

以下是使用方法:

if-else语句–用于检查答案

Print语句–用于打印输出

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.Python中的乒乓游戏

我们大多数人都听说过著名的乒乓球比赛。我们很多人都喜欢玩它。今天让我们学习如何使用python编程语言编写这款经典游戏!

在开始编码部分之前,我们首先需要安装龟模块。乌龟模块是一个Python库,它允许用户通过提供虚拟画布来创建图片和形状。

如果您还没有,可以使用pip安装库。

C:\Users\Admin>pip install turtle

请自己尝试下面代码!

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&")

输出:

如何使用Python编写简单的游戏?_第2张图片

 3.Python中的贪吃蛇游戏

这是我们小时候最喜欢的游戏。我们实际上可以通过导入两个模块来用python编写这个游戏!真酷!

让我们开始吧!

首先,我们需要安装乌龟。如果尚未安装,请打开cmd并键入以下命令。

C:\Users\Admin>pip install turtle

现在我们将安装随机模块(random module)。随机模块用于生成随机数。在cmd中键入以下命令。

C:\Users\Admin>pip install random2

编码并亲自尝试,测试这个游戏!

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

输出:

如何使用Python编写简单的游戏?_第3张图片

 结论

就这样!这些是Python中的一些简单游戏,您可以作为初学者创建这些游戏并获得一些乐趣!我们喜欢建造这些项目,我们希望你也这样做!

你可能感兴趣的:(Python编程,python游戏,python贪吃蛇,python乒乓,python编程,python)