Python good examples collection
Most of these programs are taken from or borrowed from the online source code, organized here for beginners to learn from and increase their interest in learning. Including: driving motorcycle games, Christmas cards
When running, if an error similar to the following is reported
Traceback (most recent call last):
File "……/.py", line 2, in <module>
from PIL import Image, ImageTk
ModuleNotFoundError: No module named 'XX'
Where XX is the name of the module (library, package), such as: pyglet, etc.
Instructions need to install modules (libraries, packages), such as: pip install pyglet, see the figure below:
[For installation, uninstallation and viewing of Python third-party modules (libraries, packages), see: https://blog.csdn.net/cnds123/article/details/104393385 ]
1. Driving a motorcycle game
The following resource files are needed, and save them in the res folder.
Download is provided for the convenience of readers to practice and use, the address is https://download.csdn.net/download/cnds123/15903203
The renderings are as follows:
Operating instructions: Use the arrow keys to control, "←" to decelerate, "→" to accelerate, "↑" and "↓" to turn.
The source code is as follows
import pyglet
from pyglet.window import key
from pyglet import clock
from random import randint
from math import sqrt
#------------------------------------------------------------------------
#加载资源
pyglet.resource.path = ['./res']
bg_img = pyglet.resource.image('沙漠.png')
motor_animation = pyglet.resource.animation('motor-red.gif')
box_img =pyglet.resource.image('box.png')
motor_sound = pyglet.resource.media('motor.wav', streaming=False)
alert_sound = pyglet.resource.media('alter.mp3', streaming=False)
#------------------------------------------------------------------------
#全局变量
motor_x = 0
motor_y = 40
motor_speed = 0
mileages = 0
#创建窗口
game_win = pyglet.window.Window(width=600, height=295, caption='驾驶摩托车')
#创建角色
motor = pyglet.sprite.Sprite(img=motor_animation, x=50, y=40)
box = pyglet.sprite.Sprite(img=box_img, x=500, y=10)
#文本标签
speed_label = pyglet.text.Label('Speed: 0', x=10, y=280)
mileages_label = pyglet.text.Label('Mileages: 0', x=10, y=260)
#音乐播放器
motor_player = pyglet.media.Player()
alert_player = pyglet.media.Player()
@game_win.event
def on_draw():
'''绘制游戏画面'''
global motor_x
bg_img.blit(0 - int(motor_x) % 600, 0)
bg_img.blit(600 - int(motor_x) % 600, 0)
if motor.y > box.y:
motor.draw()
box.draw()
else:
box.draw()
motor.draw()
speed_label.draw()
mileages_label.draw()
def distance(a=(0, 0), b=(0, 0)):
'''计算两点间的距离'''
return sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)
def motor_move(up_max, down_min, speed, dt):
'''摩托移动'''
global motor_speed, motor_y
if keys[key.UP]:
motor_y += 50 * dt
if motor_y > up_max: motor_y = up_max
if keys[key.DOWN]:
motor_y -= 50 * dt
if motor_y < down_min: motor_y = down_min
if keys[key.LEFT]:
motor_speed -= 324 * dt
if motor_speed < 0: motor_speed = 0
if keys[key.RIGHT]:
motor_speed += speed * dt
if motor_speed > 1620: motor_speed = 1620 #摩托车最大速度
def motor_control(dt):
'''摩托车的控制'''
global motor_speed, motor_x, motor_y, mileages
#碰撞检测和移动控制
if distance(motor.position, box.position) <= motor.width:
if (box.y < motor.y < box.y + 12):
motor_speed = 0
motor_move(50, 0, 0, dt)
elif motor.y >= box.y + 12:
motor_move(50, box.y + 12, 162, dt)
else:
motor_move(box.y, 0, 162, dt)
else:
motor_move(50, 0, 162, dt)
motor.y = motor_y
motor_x += motor_speed * dt
mileages = motor_x * 0.024
speed_label.text = 'Motor: %.3f km/h' % (motor_speed * 0.024 * 3.6)
mileages_label.text = 'Mileages: %.3f km' % (mileages / 1000)
#摩托车音效
if motor_speed > 0:
if not motor_player.playing:
motor_player.queue(motor_sound)
motor_player.play()
elif motor_speed == 0:
motor_player.next_source()
@game_win.event
def on_close():
'''游戏窗口关闭'''
motor_player.next_source()
def box_control(dt):
'''箱子的控制'''
global mileages, motor_speed
if mileages > 100 and int(mileages) % 300 == 0:
#放置箱子
box.x = 3000
box.y = motor.y - 6
#播放警报声
if not alert_player.playing:
alert_player.queue(alert_sound)
alert_player.play()
else:
#移动箱子
box.x -= motor_speed * dt
if __name__ == '__main__':
'''程序入口'''
keys = key.KeyStateHandler()
game_win.push_handlers(keys)
clock.schedule_interval(motor_control, 1/60)
clock.schedule_interval(box_control, 1/60)
pyglet.app.run()
Need to pay attention to the path relationship between the source file and the res resource folder, see the following figure:
2. Christmas card
Effect picture
The source code is as follows
import turtle as T
import random
import time
t = T.Turtle()
w = T.Screen()
t.hideturtle()
t.getscreen().tracer(5, 0)
w.screensize(bg='maroon')
t.left(90)
t.up()
t.forward(280)
t.down()
t.pensize(3)
n=100
t.color("orange","yellow")
t.begin_fill()
t.left(126)
for i in range(5):
t.forward(n/5)
t.right(144)
t.forward(n/5)
t.left(71)
t.end_fill()
t.left(60)
t.pensize(8)
t.forward(60)
t.right(20)
t.right(116)
t.pensize(6)
t.color('dark green')
n=130
for i in range(6):
time.sleep(0.5)
a=1+i/2
t.begin_fill()
t.left(90)
t.forward(n*a*0.707)
t.left(135)
t.forward(n*a)
t.left(135)
t.forward(n*a*0.707)
t.end_fill()
t.up()
t.left(90)
t.forward(n*a*0.707/3)
t.left(135)
t.forward(n*a/6)
t.left(135)
t.down()
t.up()
t.right(135)
t.forward(30)
t.right(90)
t.forward(157)
t.down()
t.color('saddlebrown')
t.begin_fill()
t.forward(80)
t.right(90)
t.forward(45)
t.right(90)
t.forward(80)
t.right(90)
t.forward(45)
t.end_fill()
t.up()
t.backward(45)
t.right(90)
t.backward(470)
t.down()
def light(l,t):
t.pensize(3)
colors = ["magenta","darkorange","red","blue"]
for i in range(l):
time.sleep(0.2)
b = 70+16*i
a = b/2*random.randint(-100,100)/100
t.up()
t.forward(b)
t.left(90)
t.forward(a)
t.down()
t.color("lightyellow",colors[i%4])
t.begin_fill()
t.circle(10)
t.end_fill()
t.up()
t.backward(a)
t.right(90)
t.backward(b)
t.down()
t.pensize(1)
def snow(m,t):
for i in range(m):
a = 400 - 800 * random.random()
b = 600 - 800 * random.random()
t.up()
t.forward(b)
t.left(90)
t.forward(a)
t.down()
t.color('white')
t.begin_fill()
t.circle(1)
t.end_fill()
t.up()
t.backward(a)
t.right(90)
t.backward(b)
light(24,t)
snow(600, t)
t.goto(-200,200)
my_word = ("Merry Christmas")
t.write(my_word,font=("Edwardian Script ITC",40,"bold"))
time.sleep(0.3)
t.goto(-100,50)
my_word = ("and")
t.write(my_word,font=("Edwardian Script ITC",50,"bold"))
time.sleep(0.3)
t.goto(-150,-100)
my_word = ("Happy New Year")
t.write(my_word,font=("Edwardian Script ITC",40,"bold"))