Python是一门高级编程语言,常被用于开发各种类型的应用程序,包括2D游戏。当编写Python代码时,字典是一个非常重要的数据类型之一。字典(Dictionary)是一个无序的key:value对集合,其中键和值都可以是任何数据类型。在Python字典中,如果无法查找到特定的键,程序通常会抛出一个错误,我们应该学会如何处理这些错误。
Python字典查询不到返回错误
在Python中,要查询一个字典中的特定键,可以使用以下代码:
dict[key]
其中,dict是字典的名称,key是要查询的键。如果指定的键不存在于字典中,Python将抛出一个KeyError,如下所示:
dict = {"name":"john", "age":30}
print(dict["height"]) # KeyError: 'height'
在这个例子中,字典中没有名为“height”的键,因此程序抛出了一个KeyError错误。为了避免这种情况,我们可以使用get()方法来代替[]操作符。get()方法将返回特定键的值,如果不存在则返回None。例如:
dict = {"name":"john", "age":30}
print(dict.get("height")) # None
在这个例子中,由于不存在名为“height”的键,get()方法返回了None。
但是,如果希望返回一个特定的默认值而不是None,可以将默认值作为get()方法的第二个参数传递。例如:
dict = {"name":"john", "age":30}
print(dict.get("height", "unknown")) # unknown
在这个例子中,由于不存在名为“height”的键,get()方法返回了默认值“unknown”。这可以让我们在字典查询时避免抛出KeyError异常。
Python 2D游戏代码大全
Python语言是一种非常灵活的编程语言,也很容易上手,许多人使用Python来写2D游戏。以下是一些常见的Python 2D游戏的代码示例:
1. Space Invaders
Space Invaders是一款古老但依然流行的2D射击游戏,以下是Space Invaders的Python代码:
import turtle
import os
# Set up the screen
wn = turtle.Screen()
wn.bgcolor("black")
wn.title("Space Invaders")
# Draw border
border_pen = turtle.Turtle()
border_pen.speed(0)
border_pen.color("white")
border_pen.penup()
border_pen.setposition(-300,-300)
border_pen.pendown()
border_pen.pensize(3)
for side in range(4):
border_pen.fd(600)
border_pen.lt(90)
border_pen.hideturtle()
# Create player turtle
player = turtle.Turtle()
player.color("blue")
player.shape("triangle")
player.penup()
player.speed(0)
player.setposition(0, -250)
player.setheading(90)
# Player movement
playerspeed = 15
def move_left():
x = player.xcor()
x -= playerspeed
if x < -280:
x = -280
player.setx(x)
def move_right():
x = player.xcor()
x += playerspeed
if x > 280:
x = 280
player.setx(x)
# Create enemy turtle
enemy = turtle.Turtle()
enemy.color("red")
enemy.shape("circle")
enemy.penup()
enemy.speed(0)
enemy.setposition(-200,250)
enemyspeed = 2
# Main game loop
while True:
# Move enemy
x = enemy.xcor()
x += enemyspeed
enemy.setx(x)
# Move enemy back and down
if enemy.xcor() > 280:
y = enemy.ycor()
y -= 40
enemyspeed *= -1
enemy.sety(y)
if enemy.xcor() < -280:
y = enemy.ycor()
y -= 40
enemyspeed *= -1
enemy.sety(y)
# Check for collision
if player.distance(enemy) < 20:
player.hideturtle()
enemy.hideturtle()
print("Game Over")
break
# Keyboard bindings
wn.listen()
wn.onkeypress(move_left, "Left")
wn.onkeypress(move_right, "Right")
2. Pong
Pong是一款简单的2D游戏,以下是Pong的Python代码:
import turtle
# Set up screen
wn = turtle.Screen()
wn.title("Pong by @TokyoEdTech")
wn.bgcolor("black")
wn.setup(width=600, height=400)
# Left paddle
left_paddle = turtle.Turtle()
left_paddle.speed(0)
left_paddle.shape("square")
left_paddle.color("white")
left_paddle.shapesize(stretch_wid=5, stretch_len=1)
left_paddle.penup()
left_paddle.goto(-250, 0)
# Right paddle
right_paddle = turtle.Turtle()
right_paddle.speed(0)
right_paddle.shape("square")
right_paddle.color("white")
right_paddle.shapesize(stretch_wid=5, stretch_len=1)
right_paddle.penup()
right_paddle.goto(250, 0)
# Ball
ball = turtle.Turtle()
ball.speed(40)
ball.shape("circle")
ball.color("white")
ball.penup()
ball.goto(0, 0)
ball.dx = 2
ball.dy = 2
# Score
left_score = 0
right_score = 0
pen = turtle.Turtle()
pen.speed(0)
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 170)
pen.write("Player 1: {} Player 2: {}".format(left_score, right_score), align="center", font=("Courier", 24, "normal"))
# Functions
def left_paddle_up():
y = left_paddle.ycor()
y += 20
left_paddle.sety(y)
def left_paddle_down():
y = left_paddle.ycor()
y -= 20
left_paddle.sety(y)
def right_paddle_up():
y = right_paddle.ycor()
y += 20
right_paddle.sety(y)
def right_paddle_down():
y = right_paddle.ycor()
y -= 20
right_paddle.sety(y)
# Keyboard bindings
wn.listen()
wn.onkeypress(left_paddle_up, "w")
wn.onkeypress(left_paddle_down, "s")
wn.onkeypress(right_paddle_up, "Up")
wn.onkeypress(right_paddle_down, "Down")
# Main game loop
while True:
wn.update()
# Move ball
ball.setx(ball.xcor() + ball.dx)
ball.sety(ball.ycor() + ball.dy)
# Border checking
if ball.ycor() > 190 or ball.ycor() < -190:
ball.dy *= -1
# Paddle collisions
if (ball.xcor() < -240 and ball.xcor() > -250) and (ball.ycor() < left_paddle.ycor() + 50 and ball.ycor() > left_paddle.ycor() - 50):
ball.dx *= -1
left_score += 1
pen.clear()
pen.write("Player 1: {} Player 2: {}".format(left_score, right_score), align="center", font=("Courier", 24, "normal"))
if (ball.xcor() > 240 and ball.xcor() < 250) and (ball.ycor() < right_paddle.ycor() + 50 and ball.ycor() > right_paddle.ycor() - 50):
ball.dx *= -1
right_score += 1
pen.clear()
pen.write("Player 1: {} Player 2: {}".format(left_score, right_score), align="center", font=("Courier", 24, "normal"))
# Winner!
if left_score == 10:
pen.clear()
pen.write("LEFT PLAYER WINS!", align="center", font=("Courier", 24, "normal"))
if right_score == 10:
pen.clear()
pen.write("RIGHT PLAYER WINS!", align="center", font=("Courier", 24, "normal"))
在上面的代码中,我们从turtle库导入一些类,例如Turtle,用于在屏幕上绘制图形。我们还使用了Python中的基本数据类型(例如整数、字符串等)和各种语言结构(例如while循环、if语句)来控制游戏的逻辑流程。这些代码可以作为Python 2D游戏开发的起点,可以根据需要进行更改和扩展。
总结
Python是一种多面手编程语言,可以用于各种应用程序,包括游戏。Python提供了一种灵活的数据类型——字典,可以存储各种类型的数据,包括键值对。当查询字典时,我们必须小心处理键不存在的情况,否则会导致程序抛出异常。Python还提供了许多库和框架,用于开发各种类型的游戏,执行各种不同的功能。 Python为游戏开发人员提供了灵活而强大的工具,可以让他们集中精力创作出令人惊叹的2D游戏。 如果你喜欢我们三七知识分享网站的文章, 欢迎您分享或收藏知识分享网站文章 欢迎您到我们的网站逛逛喔!https://www.ynyuzhu.com/
发表评论 取消回复