专业的编程技术博客社区

网站首页 > 博客文章 正文

python真的有趣(一些有趣的python代码)

baijin 2024-08-30 11:46:22 博客文章 2 ℃ 0 评论

python作为人工智能的首选语言,正因为有以下特点:
①简单,易学;
②免费,开源;
③面向对象;
④丰富的库;
⑤可扩展性;
⑥可移植性;
⑦可嵌入型;
⑧高层语言。



下面我将作了几款恶搞(有趣)型脚本送给大家,记得最终使用pyinstaller打包哟,以下恶搞型脚本使用之后电脑就会死机,切记使用!!!:

1.死命弹窗

import tkinter.messagebox
while True:
    tkinter.messagebox.showerror('Windows 错误','你的电脑正在被攻击!')

2.随机死命弹框


较第一个会好感一些,也就是桌面无限随机出现弹框

import tkinter as tk
import random
import threading
import time


def boom():
    window = tk.Tk()
    width = window.winfo_screenwidth()
    height = window.winfo_screenheight()
    a = random.randrange(0, width)
    b = random.randrange(0, height)
    window.title('你是一个傻狍子')
    window.geometry("200x50" + "+" + str(a) + "+" + str(b))
    tk.Label(window, text='你是一个傻狍子', bg='green',
             font=('宋体', 17), width=20, height=4).pack()
    window.mainloop()

threads = []
for i in range(100):
    t = threading.Thread(target=boom)
    threads.append(t)
    time.sleep(0.1)
    threads[i].start()

再来介绍一款py实用之处,比如查询快递信息,运行之后在界面输入订单编号,程序会自动打开chorme浏览器,之后会打印出快递详情信息:

# 根据快递单号查询物流信息
def get_screenshot_and_info():
    chrome_driver = r'D:\python\pycharm2020\chromedriver.exe'  # chromedriver的路径
    options = webdriver.ChromeOptions()
    # 关闭左上方 Chrome 正受到自动测试软件的控制的提示
    options.add_experimental_option('useAutomationExtension', False)
    options.add_experimental_option("excludeSwitches", ['enable-automation'])
    # 开启浏览器对象
    browser = webdriver.Chrome(options=options, executable_path=chrome_driver)
    # 访问这个url
    browser.get('https://www.kuaidi100.com/')
    # 显示等待
    wait = WebDriverWait(browser, 5)
    wait.until(ec.presence_of_element_located((By.ID, 'menu-track')))
    # 窗口最大化
    browser.maximize_window()
    browser.find_element_by_name('postid').send_keys(nums)
    browser.find_element_by_id('query').click()
    time.sleep(1)
    browser.find_element_by_id('query').click()
    time.sleep(2)
    browser.execute_script("window.scrollBy(0, 488)")
    # 截图
    browser.get_screenshot_as_file(filename='info.png')
    items = browser.find_elements_by_xpath('//table[@class="result-info"]/tbody/tr')
    print('物流信息查询结果如下:\n')
    for item in items:
        time_ = item.find_element_by_xpath('.//td[1]').text.replace('\n', ' ')
        contex = item.find_element_by_xpath('.//td[3]').text
        print(f'时间:{time_}')
        print(f'状态:{contex}\n')
    browser.quit()
    # 显示截图
    src = cv.imread(filename='info.png')
    src = cv.resize(src, None, fx=0.7, fy=0.7)
    cv.imshow('result', src)
    cv.waitKey(0)

最后再来搞一下小时候经常玩的游戏《贪吃蛇》:

#!/usr/bin/env python
import pygame,sys,time,random
from pygame.locals import *
# 定义颜色变量
redColour = pygame.Color(255,0,0)
blackColour = pygame.Color(0,0,0)
whiteColour = pygame.Color(255,255,255)
greyColour = pygame.Color(150,150,150)

# 定义gameOver函数
def gameOver(playSurface):
 gameOverFont = pygame.font.Font('arial.ttf',72)
 gameOverSurf = gameOverFont.render('Game Over', True, greyColour)
 gameOverRect = gameOverSurf.get_rect()
 gameOverRect.midtop = (320, 10)
 playSurface.blit(gameOverSurf, gameOverRect)
 pygame.display.flip()
 time.sleep(5)
 pygame.quit()
 sys.exit()

# 定义main函数
def main():
 # 初始化pygame
 pygame.init()
 fpsClock = pygame.time.Clock()
 # 创建pygame显示层
 playSurface = pygame.display.set_mode((640,480))
 pygame.display.set_caption('Raspberry Snake')

 # 初始化变量
 snakePosition = [100,100]
 snakeSegments = [[100,100],[80,100],[60,100]]
 raspberryPosition = [300,300]
 raspberrySpawned = 1
 direction = 'right'
 changeDirection = direction
 while True:
 # 检测例如按键等pygame事件
 for event in pygame.event.get():
 if event.type == QUIT:
 pygame.quit()
 sys.exit()
 elif event.type == KEYDOWN:
 # 判断键盘事件
 if event.key == K_RIGHT or event.key == ord('d'):
 changeDirection = 'right'
 if event.key == K_LEFT or event.key == ord('a'):
 changeDirection = 'left'
 if event.key == K_UP or event.key == ord('w'):
 changeDirection = 'up'
 if event.key == K_DOWN or event.key == ord('s'):
 changeDirection = 'down'
 if event.key == K_ESCAPE:
 pygame.event.post(pygame.event.Event(QUIT))
 # 判断是否输入了反方向
 if changeDirection == 'right' and not direction == 'left':
 direction = changeDirection
 if changeDirection == 'left' and not direction == 'right':
 direction = changeDirection
 if changeDirection == 'up' and not direction == 'down':
 direction = changeDirection
 if changeDirection == 'down' and not direction == 'up':
 direction = changeDirection
 # 根据方向移动蛇头的坐标
 if direction == 'right':
 snakePosition[0] += 20
 if direction == 'left':
 snakePosition[0] -= 20
 if direction == 'up':
 snakePosition[1] -= 20
 if direction == 'down':
 snakePosition[1] += 20
 # 增加蛇的长度
 snakeSegments.insert(0,list(snakePosition))
 # 判断是否吃掉了树莓
 if snakePosition[0] == raspberryPosition[0] and snakePosition[1] == raspberryPosition[1]:
 raspberrySpawned = 0
 else:
 snakeSegments.pop()
 # 如果吃掉树莓,则重新生成树莓
 if raspberrySpawned == 0:
 x = random.randrange(1,32)
 y = random.randrange(1,24)
 raspberryPosition = [int(x*20),int(y*20)]
 raspberrySpawned = 1
 # 绘制pygame显示层
 playSurface.fill(blackColour)
 for position in snakeSegments:
 pygame.draw.rect(playSurface,whiteColour,Rect(position[0],position[1],20,20))
 pygame.draw.rect(playSurface,redColour,Rect(raspberryPosition[0], raspberryPosition[1],20,20))

 # 刷新pygame显示层
 pygame.display.flip()
 # 判断是否死亡
 if snakePosition[0] > 620 or snakePosition[0] < 0:
 gameOver(playSurface)
 if snakePosition[1] > 460 or snakePosition[1] < 0:
 for snakeBody in snakeSegments[1:]:
 if snakePosition[0] == snakeBody[0] and snakePosition[1] == snakeBody[1]:
 gameOver(playSurface)
 # 控制游戏速度
 fpsClock.tick(5)

if __name__ == "__main__":
 main()

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表