使用借记卡立即购买比特币

以下是Python实现坦克大战的完整代码:

import pygame
from random import randint
# 初始化Pygame库
pygame.init()
# 定义游戏窗口大小和标题
screen_width, screen_height = 640, 480
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Tank Battle")
# 加载图像资源
tank_img = pygame.image.load('tank.png').convert_alpha()
bullet_img = pygame.image.load('bullet.png').convert_alpha()
explosion_imgs = [pygame.image.load('explosion1.png').convert_alpha(),
                  pygame.image.load('explosion2.png').convert_alpha(),
                  pygame.image.load('explosion3.png').convert_alpha()]
# 定义颜色常量
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 定义游戏对象类
class GameObject:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def draw(self):
        pass
# 定义坦克类,继承自GameObject类
class Tank(GameObject):
    def __init__(self, x, y):
        super().__init__(x, y)
        self.direction = 'up'
        self.speed = 5
    # 根据方向移动坦克位置,并检查是否越界或碰到墙壁
    def move(self):
        if self.direction == 'up':
            if self.y > 0:
                self.y -= self.speed
            else:
                self.y = 0
        
        elif self.direction == 'down':
            if self.y < screen_height - tank_img.get_height():
                self.y += self.speed
            else:
                self.y = screen_height - tank_img.get_height()
        
        elif self.direction == 'left':
            if self.x > 0:
                self.x -= self.speed
            else:
                self.x = 0
        
        elif self.direction == 'right':
            if self.x < screen_width - tank_img.get_width():
                self.x += self.speed
            else:
                self.x = screen_width - tank_img.get_width()
    # 发射子弹
    def fire(self):
        bullet_x, bullet_y = 0, 0
        
        # 根据坦克方向计算子弹位置
        if self.direction == 'up':
            bullet_x = self.x + tank_img.get_width() / 2 - bullet_img.get_width() / 2
            bullet_y = self.y
        
        elif self.direction == 'down':
            bullet_x = self.x + tank_img.get_width() / 2 - bullet_img.get_width() / 2
            bullet_y = self.y + tank_img.get_height()
        
        elif self.direction == 'left':
            bullet_x = self.x 
            bullet_y =self. y + tank_img.get_height() / 2 - bullet_img.get_height() / 2
        
        elif self.direction == 'right':
            bullet_x =self. x +tank_ img. get_ width () 
            bullet_y= sel f. y +tank_ img. get_ height ()/2- bul let _i mg. ge t_hei ght()/2
            
        return Bullet(bullet_x, bullet_y, direction=self.direction)
    # 绘制坦克图像到屏幕上
    def draw(self):
        rotated_tank_image, rotated_tank_rect = self.rotate_image(tank_img, (self.x, self.y), self.direction)
        screen.blit(rotated_tank_image, rotated_tank_rect)
    # 根据方向旋转坦克图像
    def rotate_image(self, image, pos, direction):
        if direction == 'up':
            return image, pygame.Rect(pos[0], pos[1], image.get_width(), image.get_height())
        
        elif direction == 'down':
            return pygame.transform.flip(image, False, True), pygame.Rect(pos[0], pos[1], image.get_width(), image.get_height())
        
        elif direction == 'left':
            return pygame.transform.rotate(image, 90), pygame.Rect(pos[0], pos[1], image.get_height(), image.get_width())
        
        elif direction == 'right':
            return pygame.transform.rotate(image, -90), pygame.Rect(pos[0], pos[1], image.get_height(), image.get_width())
# 定义子弹类,继承自GameObject类
class Bullet(GameObject):
    def __init__(self, x, y, direction='up'):
        super().__init__(x, y)
        self.speed = 10
        self.direction = direction
    # 移动子弹位置,并检查是否越界或碰到墙壁
    def move(self):
        if self.direction == 'up':
            if self.y > 0:
                self.y -= self.speed
            else:
                return False
        
        elif self.direction == 'down':
            if self.y < screen_height - bullet_img.get_height():
                self.y += self.speed
            else:
                return False
        
        elif self.direction == 'left':
            if self.x > 0:
                self.x -= self.speed
            else:
                return False
        
        elif self.direction == 'right':
            if self.x < screen_width - bullet_img.get_width():
                self.x += self.speed
            else:
                return False
        
        return True
    # 绘制子弹图像到屏幕上
    def draw(self):
        screen.blit(bullet_img, (self.x, self.y))
# 定义爆炸类,继承自GameObject类
class Explosion(GameObject):
    def __init__(self, x, y):
        super().__init__(x, y)
        self.frame_index = 0
        self.frame_count = len(explosion_imgs)
        self.frame_duration = 3
        self.frame_timer = 0
    
    # 更新爆炸动画帧
    def update(self):
        self.frame_timer += 1
        
        if self.frame_timer >= self.frame_duration:
            if self.frame_index < self.frame_count - 1:
                self.frame_index += 1
            else:
                return False
            
            self.frame_timer = 0
        
        return True
    
    # 绘制当前爆炸动画帧到屏幕上
    def draw(self):
        screen.blit(explosion_imgs[self.frame_index], (self.x, self.y))
# 定义障碍物类,继承自GameObject类
class Obstacle(GameObject):
    def __init__(self, x, y):
        super().__init__(x, y)
    # 绘制障碍物图像到屏幕上
    def draw(self):
        pygame.draw.rect(screen, black, (self.x, self.y, 30, 30))
# 创建游戏对象实例:坦克、敌方坦克、子弹、爆炸和障碍物
player_tank = Tank(screen_width/2-tank_img.get_width()/2, screen_height-tank_img.get_height())
enemy_tank = Tank(randint(0, screen_width - tank_img.get_width()), 0)
enemy_bullet = None
explosion = None
obstacles = []
for i in range(10):
    obstacles.append(Obstacle(randint(0, screen_width-30), randint(0, screen_height-30))))
# 定义游戏循环变量和时钟对象
running = True
clock = pygame.time.Clock()
# 游戏循环
while running:
    # 处理事件:按键、关闭窗口等
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                player_tank.direction = 'up'
            
            elif event.key == pygame.K_DOWN:
                player_tank.direction = 'down'
            
            elif event.key == pygame.K_LEFT:
                player_tank.direction = 'left'
            
            elif event.key == pygame.K_RIGHT:
                player_tank.direction ='right'
            
            elif event.key == pygame.K_SPACE and enemy_bullet is None:
                enemy_bullet= enemy _tank.fire()
    
    # 移动坦克和子弹位置,并检查是否发生碰撞或越界等情况,处理相关逻辑
    if enemy_bullet is not None and not enemy_bullet.move():
        if player_tank.x < enemy_bullet.x + bullet_img.get_width() < player_tank.x + tank_img.get_width() and \
           player_tank.y < enemy_bullet.y + bullet_img.get_height() < player_tank.y + tank_img.get_height():
            explosion = Explosion(player_tank.x, player_tank.y)
            player_tank.x = screen_width / 2 - tank_img.get_width() / 2
            player_tank.y = screen_height - tank_img.get_height()
        enemy_bullet = None
    
    if enemy_tank is not None and randint(0, 100) > 95:
        enemy_bullet = enemy_tank.fire()
    
    if enemy_bullet is not None and not enemy_bullet.move():
        if player_tank.x < enemy_bullet.x + bullet_img.get_width() < player_tank.x + tank_img.get_width() and \
           player_tank.y < enemy_bullet.y + bullet_img.get_height() < player_tank.y + tank_img.get_height():
            explosion = Explosion(player_tank.x, player_tank.y)
            player_tank.x = screen_width/2-tank_img.get_width()/2
            player _tank. y=screen_ height-tan k_i mg. get_ height ()
            
        elif (enemy_bullet.x<0 or enemy_bullet.x>screen_width or 
              enemy _bullet .y<0 or ene my_bul let .y>scr een_ heig ht):
                enemy _bullet=None
                
    for obstacle in obstacles:
        if (obstacle. x<player _tank. x+ta nk_i mg. get_ width ()and 
            obstacle. x+3 0>pla yer_ tank .x and
            obstacle .y<pl ayer_ta nk.y+t ank_i mg.g et_hei ght( )and 
            obs tacle .y+30>p layer_ tan k.y ):
                 if pl ayer_ta nk.di rect ion=='up':
                     play er_ta nk. y=obstacle . y+t ank_i mg.ge t_ height ()
                 elif player_tank.direction=='down':
                     player _tank. y= obstacle.y- tank_img. get_height()
                 elif player_tank.direction =='left':
                     player _tank. x=obstacle .x+30
                 elif pla yer_ta nk.di rect ion=='right':
                     play er_ta nk.x=o bs tac le.x-t an k_i mg. get_ width ()
                     
        if (enemy_bullet is not None and 
            obstacle .x<en emy_b ul let .x+b ullet _img.get_ widt h()and 
            obs tacle .x+3 0>ene my_bul let .x and
            obstacle.y < enemy_bullet.y + bullet_img.get_height() < obstacle.y + 30):
                explosion = Explosion(obstacle.x, obstacle.y)
                obstacles.remove(obstacle)
                enemy_bullet = None
    
    if explosion is not None:
        if not explosion.update():
            explosion = None
    
    # 绘制游戏场景和对象
    screen.fill(white)
    for obstacle in obstacles:
        obstacle.draw()
    
    if enemy_tank is not None:
        enemy_tank.move()
        enemy_tank.draw()
    
    if enemy_bullet is not None:
        enemy_bullet.draw()
    if explosion is not None:
        explosion.draw()
    player_tank.move()
    player_tank.draw()
    pygame.display.update()
    # 设置游戏帧率
    clock.tick(60)
# 退出Pygame库
pygame.quit()

以上代码实现了基本的坦克大战游戏功能,包括坦克移动、发射子弹、障碍物碰撞检测等。但仍有很多改进和扩展的空间,例如增加多个敌方坦克、支持双人游戏模式等。

澳大利亚和比特币

def quickSort(array):
    if len(array) <= 1:
        return array
    pivot = array[0]
    left = [x for x in array if x < pivot]
    right = [x for x in array if x > pivot]
    return quickSort(left) + [pivot] + quickSort(right)

快速排序算法是时间复杂度为O(n * log n),因此在大多数情况下,它都能够比其他算法更快地完成排序任务。

比特币挖掘者

今天记录几段工作生活中常用的python代码,都是最为基础的功能和操作,而且大多还都是出现频率比较高的,很多都是可以拿来直接使用或者简单修改就可以放到自己的项目当中

2010年比特币价格

很多时候我们需要批量生成日期,方法有很多,这里分享两段代码

获取过去 N 天的日期

import datetime

def get_nday_list(n):
    before_n_days = []
    for i in range(1, n + 1)[::-1]:
        before_n_days.append(str(datetime.date.today() - datetime.timedelta(days=i)))
    return before_n_days

a = get_nday_list(30)
print(a)

Output:

[‘2021-12-23’, ‘2021-12-24’, ‘2021-12-25’, ‘2021-12-26’, ‘2021-12-27’, ‘2021-12-28’, ‘2021-12-29’, ‘2021-12-30’, ‘2021-12-31’, ‘2022-01-01’, ‘2022-01-02’, ‘2022-01-03’, ‘2022-01-04’, ‘2022-01-05’, ‘2022-01-06’, ‘2022-01-07’, ‘2022-01-08’, ‘2022-01-09’, ‘2022-01-10’, ‘2022-01-11’, ‘2022-01-12’, ‘2022-01-13’, ‘2022-01-14’, ‘2022-01-15’, ‘2022-01-16’, ‘2022-01-17’, ‘2022-01-18’, ‘2022-01-19’, ‘2022-01-20’, ‘2022-01-21’]

使用信用卡购买比特币,无需验证

import datetime

def create_assist_date(datestart = None,dateend = None):
    # 创建日期辅助表

    if datestart is None:
        datestart = '2016-01-01'
    if dateend is None:
        dateend = datetime.datetime.now().strftime('%Y-%m-%d')

    # 转为日期格式
    datestart=datetime.datetime.strptime(datestart,'%Y-%m-%d')
    dateend=datetime.datetime.strptime(dateend,'%Y-%m-%d')
    date_list = []
    date_list.append(datestart.strftime('%Y-%m-%d'))
    while datestart<dateend:
        # 日期叠加一天
        datestart+=datetime.timedelta(days=+1)
        # 日期转字符串存入列表
        date_list.append(datestart.strftime('%Y-%m-%d'))
    return date_list

d_list = create_assist_date(datestart='2021-12-27', dateend='2021-12-30')
print(d_list)

Output:

[‘2021-12-27’, ‘2021-12-28’, ‘2021-12-29’, ‘2021-12-30’]

拥有 1 BTC 的比特币地址

保存数据到 CSV 是太常见的操作了,分享一段我个人比较喜欢的写法

python

def save_data(data, date):
    if not os.path.exists(r'2021_data_%s.csv' % date):
        with open("2021_data_%s.csv" % date, "a+", encoding='utf-8') as f:
            f.write("标题,热度,时间,url\n")
            for i in data:
                title = i["title"]
                extra = i["extra"]
                time = i['time']
                url = i["url"]
                row = '{},{},{},{}'.format(title,extra,time,url)
                f.write(row)
                f.write('\n')
    else:
        with open("2021_data_%s.csv" % date, "a+", encoding='utf-8') as f:
            for i in data:
                title = i["title"]
                extra = i["extra"]
                time = i['time']
                url = i["url"]
                row = '{},{},{},{}'.format(title,extra,time,url)
                f.write(row)
                f.write('\n')

方舟 比特币 马斯克

Pyecharts 作为 Echarts 的优秀 Python 实现,受到众多开发者的青睐,用 Pyecharts 作图时,使用一个舒服的背景也会给我们的图表增色不少

以饼图为例,通过添加 JavaScript 代码来改变背景颜色

def pie_rosetype(data) -> Pie:
    background_color_js = (
    "new echarts.graphic.LinearGradient(0, 0, 0, 1, "
    "[{offset: 0, color: '#c86589'}, {offset: 1, color: '#06a7ff'}], false)"
)
    c = (
        Pie(init_opts=opts.InitOpts(bg_color=JsCode(background_color_js)))
        .add(
            "",
            data,
            radius=["30%", "75%"],
            center=["45%", "50%"],
            rosetype="radius",
            label_opts=opts.LabelOpts(formatter="{b}: {c}"),
        )
        .set_global_opts(title_opts=opts.TitleOpts(title=""),
                        )
    )
    return c

比特币更新

据统计,requests 库是 Python 家族里被引用的最多的第三方库,足见其江湖地位之高大!

发送 GET 请求

python

import requests


headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36',
  'cookie': 'some_cookie'
}
response = requests.request("GET", url, headers=headers)

发送 POST 请求

python

import requests


payload={}
files=[]
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36',
  'cookie': 'some_cookie'
}
response = requests.request("POST", url, headers=headers, data=payload, files=files)

根据某些条件循环请求,比如根据生成的日期

python

def get_data(mydate):
    date_list = create_assist_date(mydate)
    url = "https://test.test"
    files=[]
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36',
        'cookie': ''
        }
    for d in date_list:
        payload={'p': '10',
        'day': d,
        'nodeid': '1',
        't': 'itemsbydate',
        'c': 'node'}
        for i in range(1, 100):
            payload['p'] = str(i)
            print("get data of %s in page %s" % (d, str(i)))
            response = requests.request("POST", url, headers=headers, data=payload, files=files)
            items = response.json()['data']['items']
            if items:
                save_data(items, d)
            else:
                break

比特币价格减半图表

山寨币与比特币负相关

连接 Redis

import redis


def redis_conn_pool():
    pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
    rd = redis.Redis(connection_pool=pool)
    return rd

写入 Redis

from redis_conn import redis_conn_pool


rd = redis_conn_pool()
rd.set('test_data', 'mytest')

0.09428802 比特币 为 美元

连接 MongoDB

from pymongo import MongoClient


conn = MongoClient("mongodb://%s:%s@ipaddress:49974/mydb" % ('username', 'password'))
db = conn.mydb
mongo_collection = db.mydata

批量插入数据

res = requests.get(url, params=query).json()
commentList = res['data']['commentList']
mongo_collection.insert_many(commentList)

2010年1000比特币

连接 MySQL

import MySQLdb

# 打开数据库连接
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' )

# 使用cursor()方法获取操作游标 
cursor = db.cursor()
执行 SQL 语句

# 使用 execute 方法执行 SQL 语句
cursor.execute("SELECT VERSION()")

# 使用 fetchone() 方法获取一条数据
data = cursor.fetchone()

print "Database version : %s " % data

# 关闭数据库连接
db.close()

Output:

Database version : 5.0.45

如何将比特币变成现金

整理文件涉及需求的比较多,这里分享的是将本地多个 CSV 文件整合成一个文件

import pandas as pd
import os


df_list = []
for i in os.listdir():
    if "csv" in i:
        day = i.split('.')[0].split('_')[-1]
        df = pd.read_csv(i)
        df['day'] = day
        df_list.append(df)
df = pd.concat(df_list, axis=0)
df.to_csv("total.txt", index=0)

方舟投资比特币目标价格

多线程也有很多实现方式,我们选择自己最为熟悉顺手的方式即可

import threading
import time

exitFlag = 0

class myThread (threading.Thread):
    def __init__(self, threadID, name, delay):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.delay = delay
    def run(self):
        print ("开始线程:" + self.name)
        print_time(self.name, self.delay, 5)
        print ("退出线程:" + self.name)

def print_time(threadName, delay, counter):
    while counter:
        if exitFlag:
            threadName.exit()
        time.sleep(delay)
        print ("%s: %s" % (threadName, time.ctime(time.time())))
        counter -= 1

# 创建新线程
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

# 开启新线程
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print ("退出主线程")

比特币受到监管

异步爬取网站

import asyncio
import aiohttp
import aiofiles

async def get_html(session, url):
    try:
        async with session.get(url=url, timeout=8) as resp:
            if not resp.status // 100 == 2:
                print(resp.status)
                print("爬取", url, "出现错误")
            else:
                resp.encoding = 'utf-8'
                text = await resp.text()
                return text
    except Exception as e:
        print("出现错误", e)
        await get_html(session, url)

使用异步请求之后,对应的文件保存也需要使用异步,即是一处异步,处处异步

async def download(title_list, content_list):
    async with aiofiles.open('{}.txt'.format(title_list[0]), 'a',
                             encoding='utf-8') as f:
        await f.write('{}'.format(str(content_list)))

以上就是平时用的最多的代码片段,希望对你有所帮助

什么是比特币以及它是如何运作的

欢迎使用 WordPress。这是您的第一篇文章。编辑或删除它,然后开始写作吧!