python的一些小游戏

python的一些简单用法分享

1. 链接Linux服务器

下载paramiko模块

pip install paramiko

链接Linux服务器

import paramiko

hostname = '192.168.106.128'
username = 'root'
password = '123456'

# 创建SSH客户端
client = paramiko.SSHClient()

# 允许链接不在know_hosts文件里的主机
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# 链接服务器
client.connect(hostname=hostname,username=username,password=password)

# 执行命令,
stdin, stdout, stderr = client.exec_command('ls -l /opt/')

# 获取输出,正确的放入到stdout 错误的放入到stderr中
print(stdout.read().decode())

# 关闭链接
client.close()

2. 链接mysql数据库

链接数据库,并将json格式的数据存储到MySQL数据库中

import json
import pymysql as mysql

conn = mysql.connect(
            host='IP',
            port= 3306,
            user='用户名',
            password='密码',
            database='数据库名',
            charset='utf8'
        )
cur = conn.cursor()

# 数据存储的方法,table是表名,item是json数据
def save(table,**item):
    sql='insert into `%s`(%s) values(%s)'
    #fields = ','.join(item)
    fields='`'+('`,`'.join(item))+'`'
    values=','.join(['%%(%s)s' % k for k in item])
    #print('insert :', sql %(table,fields,values),item)
    cur.execute(sql %(table,fields,values),item)
    cur.execute('commit')
    return cur.rowcount > 0


# 读取json数据
with open('D:/jsonn.txt','r', encoding='utf-8') as f:
    data = f.read()
    data_dict = json.loads(data)
    print(data_dict)


for i in data_dict['root']:
    save('test_jsonn',**i)
    #print(i)

3. 九九乘法表

3.1 while循环实现

# 九九乘法表
i = 1
while i <= 9:
    j = 1
    while j <= i:
        print(f'{j} * {i} = {j*i}\t', end = '')
        j += 1
    i += 1
    print()

3.2 for循环实现

# for循环九九乘法表
for i in range(1,10):
    for j in range(1,i+1):
        print(f'{j} * {i} = {j*i}\t', end ='')
    print()

在这里插入图片描述

4. 猜数字游戏

# 猜数字游戏
import random
num = random.randint(1,100)
count = 0 
flag = True

while flag:
    guess_num = int(input('请输入你要猜的数字:'))
    if guess_num == num:
        print('恭喜你猜对了!')
        flag = False
    else:
        if guess_num > num:
            print('猜大了')
        else:
            print('猜小了')
    count += 1
print(f'你总共猜了{count}次!')

5. 创建删除目录

import os
# 删除文件
if os.path.exists('E:\spider.txt'):
	os.remove('E:\spider.txt')
else:
    print('File is not exists!')
    
# 创建文件

if not os.path.exists('E:\spider.txt'):
	os.mkdir('E:\spider.txt')
else:
    print('File is  exists!')

6. 笨办法学python的一个熊出没游戏

# 定义一个熊出没的游戏
from sys import exit

# 定义房间金币函数
def gold_room():
    print ("This room is full of gold. How much do you take?")  # 这个房间充满了金币

    next = input("How much gold do you want ")  # 输入你要的金币
    if next.isdigit():
        if next < '50':
            print("Nice,you're not greedy,you win!")  # nice,你不是贪婪的人  你赢了
            exit(0)
        else:
            dead("You greedy bastard!")  # 你太贪婪了
    else:
        dead("Man,learn to type a number.")   # 先生,请输入数字


# 定义熊房间函数   
def bear_room():

    # 这里有一只熊,这个熊有一堆蜂蜜,胖熊在门的另一边,你如何移动熊
    print("""
    There is a bear here.
    The bear has a bunch of honey.
    The fat bear is in front of another door.
    How are you going to move the bear?
    """)
   
    bear_moved = False
    while True:
        next = input("How are you doing?")  # 你要如何做
        if next == "take honey":   # 带蜂蜜
            dead("The bear looks at you then slaps your face off.")  # 这个熊看着你并扇了你一个耳光
        elif next == "taunt bear" and not bear_moved:  # 嘲讽熊 和 True
            print("The bear has moved from the door,You can go through it now")  # 熊走了 你可以通过了
            bear_moved = True
        elif next == "taunt bear" and bear_moved:
            dead("The bear gets pissed off and chews your leg off.") # 熊咬断了你的腿
        elif next == "open door" and bear_moved:   # 打开门
            gold_room()
        else:
            print("I got no idea what that means.")  # 我没注意了
            dead("没时间了,熊来了!")

# 定义克鲁斯房间
def cthulhu_room():
    '''
    在这里你看到了邪恶的克图鲁。
    他,它,任何东西盯着你看,你就会发疯。
    你是逃命还是吃脑袋?
    '''
    print("""
    Here you see the great evil Cthulhu.
    He, it, whatever stares at you and you go insane.
    Do you flee for your life or eat your head?
    """)
    next = input("Do you what")  # 你想怎么做
    if "flee" in next:
        start()
    elif "head" in next:
        dead("Well that was tasty!")  # 太好吃了
    else:
        cthulhu_room()

# 定义死亡提醒函数
def dead(why):
    print(f"{why} , Goodbye!")
    exit(0)


# 定义开始函数
def start():
    '''
    你在一个漆黑的房间里
    在你的左右两侧都有一扇门
    你选择哪一个!
    '''
    print("""
    You are in a dark room.
    There is a door to your right and left.
    Which one do you take!
    """)
    next = input("输入你的选择?")
    if next == "left":
        bear_room()
    elif next == "right":
        cthulhu_room()
    else:
        dead("You stumble around the room until you starve.")  # 你在房间颠颠撞撞,知道饿死


start()
  • 9
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Eason-Python

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值