给我的所有粉丝们写了一封信

感谢大家一直以来对我的支持和鼓励!

身为程序猿我当然要用程序来表达对你们的感谢!

这篇文章仅有粉丝可见!代码都是以前发布过的!懂得都懂!

1、“送给你小心心”

运行效果

源代码

import random
from math import sin, cos, pi, log
from tkinter import *
CANVAS_WIDTH = 640 # 宽
CANVAS_HEIGHT = 480 # 高
CANVAS_CENTER_X = CANVAS_WIDTH / 2
CANVAS_CENTER_Y = CANVAS_HEIGHT / 2
IMAGE_ENLARGE = 11 # 放大比例
HEART_COLOR = '#FF69B4'
def heart_function(t, shrink_ratio: float = IMAGE_ENLARGE):
  """
  “爱心函数生成器”
  :param shrink_ratio: 放大比例
  :param t: 参数
  :return: 坐标
  """
  # 基础函数
  x = 16 * (sin(t) ** 3)
  y = -(13 * cos(t) - 5 * cos(2 * t) - 2 * cos(3 * t) - cos(4 * t))
  # 放大
  x *= shrink_ratio
  y *= shrink_ratio
  # 移到画布中央
  x += CANVAS_CENTER_X
  y += CANVAS_CENTER_Y
  return int(x), int(y)
def scatter_inside(x, y, beta=0.15):
  """
  随机内部扩散
  :param x: 原x
  :param y: 原y
  :param beta: 强度
  :return: 新坐标
  """
  ratio_x = - beta * log(random.random())
  ratio_y = - beta * log(random.random())
  dx = ratio_x * (x - CANVAS_CENTER_X)
  dy = ratio_y * (y - CANVAS_CENTER_Y)
  return x - dx, y - dy
def shrink(x, y, ratio):
  """
  抖动
  :param x: 原x
  :param y: 原y
  :param ratio: 比例
  :return: 新坐标
  """
  force = -1 / (((x - CANVAS_CENTER_X) ** 2 + (y - CANVAS_CENTER_Y) ** 2) ** 0.6)
  dx = ratio * force * (x - CANVAS_CENTER_X)
  dy = ratio * force * (y - CANVAS_CENTER_Y)
  return x - dx, y - dy
def curve(p):
  """
  自定义曲线函数,调整跳动周期
  :param p: 参数
  :return: 正弦
  """
  return 2 * (2 * sin(4 * p)) / (2 * pi)
class Heart:
  """
  爱心类
  """
  def __init__(self, generate_frame=20):
    self._points = set() # 原始爱心坐标集合
    self._edge_diffusion_points = set() # 边缘扩散效果点坐标集合
    self._center_diffusion_points = set() # 中心扩散效果点坐标集合
    self.all_points = {} # 每帧动态点坐标
    self.build(2000)
    self.random_halo = 1000
    self.generate_frame = generate_frame
    for frame in range(generate_frame):
      self.calc(frame)
  def build(self, number):
    # 爱心
    for _ in range(number):
      t = random.uniform(0, 2 * pi) # 随机不到的地方造成爱心有缺口
      x, y = heart_function(t)
      self._points.add((x, y))
    # 爱心内扩散
    for _x, _y in list(self._points):
      for _ in range(3):
        x, y = scatter_inside(_x, _y, 0.05)
        self._edge_diffusion_points.add((x, y))
    # 爱心内再次扩散
    point_list = list(self._points)
    for _ in range(4000):
      x, y = random.choice(point_list)
      x, y = scatter_inside(x, y, 0.17)
      self._center_diffusion_points.add((x, y))
  @staticmethod
  def calc_position(x, y, ratio):
    # 调整缩放比例
    force = 1 / (((x - CANVAS_CENTER_X) ** 2 + (y - CANVAS_CENTER_Y) ** 2) ** 0.520) # 魔法参数
    dx = ratio * force * (x - CANVAS_CENTER_X) + random.randint(-1, 1)
    dy = ratio * force * (y - CANVAS_CENTER_Y) + random.randint(-1, 1)
    return x - dx, y - dy
  def calc(self, generate_frame):
    ratio = 10 * curve(generate_frame / 10 * pi) # 圆滑的周期的缩放比例
    halo_radius = int(4 + 6 * (1 + curve(generate_frame / 10 * pi)))
    halo_number = int(3000 + 4000 * abs(curve(generate_frame / 10 * pi) ** 2))
    all_points = []
    # 光环
    heart_halo_point = set() # 光环的点坐标集合
    for _ in range(halo_number):
      t = random.uniform(0, 2 * pi) # 随机不到的地方造成爱心有缺口
      x, y = heart_function(t, shrink_ratio=11.6) # 魔法参数
      x, y = shrink(x, y, halo_radius)
      if (x, y) not in heart_halo_point:
        # 处理新的点
        heart_halo_point.add((x, y))
        x += random.randint(-14, 14)
        y += random.randint(-14, 14)
        size = random.choice((1, 2, 2))
        all_points.append((x, y, size))
    # 轮廓
    for x, y in self._points:
      x, y = self.calc_position(x, y, ratio)
      size = random.randint(1, 3)
      all_points.append((x, y, size))
    # 内容
    for x, y in self._edge_diffusion_points:
      x, y = self.calc_position(x, y, ratio)
      size = random.randint(1, 2)
      all_points.append((x, y, size))
    for x, y in self._center_diffusion_points:
      x, y = self.calc_position(x, y, ratio)
      size = random.randint(1, 2)
      all_points.append((x, y, size))
    self.all_points[generate_frame] = all_points
  def render(self, render_canvas, render_frame):
    for x, y, size in self.all_points[render_frame % self.generate_frame]:
      render_canvas.create_rectangle(x, y, x + size, y + size, width=0, fill=HEART_COLOR)
def draw(main: Tk, render_canvas: Canvas, render_heart: Heart, render_frame=0):
  render_canvas.delete('all')

  render_heart.render(render_canvas, render_frame)

  main.after(160, draw, main, render_canvas, render_heart, render_frame + 1)
if __name__ == '__main__':
  root = Tk() # 一个Tk
  canvas = Canvas(root, bg='black', height=CANVAS_HEIGHT, width=CANVAS_WIDTH)
  canvas.pack()
  heart = Heart() # 心
  draw(root, canvas, heart)
  root.mainloop()

 2、“送你花一朵”

运行效果

源代码

 


import turtle as t
#画花茎
t.pensize(5)
t.pencolor('brown')
t.penup()
t.goto(-35,-200)
t.pendown()
t.goto(-35,0)
#画花瓣
t.pencolor('red')
t.goto(0,0)
for i in range(5):
    t.dot(100)
    t.lt(72)
    t.penup
    t.forward(70)
    t.pendown
#画华芯
t.goto(-35,50)
t.pencolor('yellow')
t.begin_fill()
t.dot(100)
#画叶子
t.penup()
t.goto(-35,-200)
t.pendown()
t.fillcolor('green')
t.pencolor('green')
t.begin_fill()
t.seth(0)
t.circle(150,80)
t.seth(180)
t.circle(150,80)
t.seth(180)
t.circle(-150,80)
t.seth(0)
t.circle(-150,80)
t.end_fill()
t.done()

3、献给粉丝的贪吃蛇游戏

运行效果

源代码

import random
import pygame
import sys
from pygame.locals import *

Snakespeed = 9
Window_Width = 800
Window_Height = 500
Cell_Size = 20  # Width and height of the cells
# Ensuring that the cells fit perfectly in the window. eg if cell size was
# 10     and window width or window height were 15 only 1.5 cells would
# fit.
assert Window_Width % Cell_Size == 0, "Window width must be a multiple of cell size."
# Ensuring that only whole integer number of cells fit perfectly in the window.
assert Window_Height % Cell_Size == 0, "Window height must be a multiple of cell size."
Cell_W = int(Window_Width / Cell_Size)  # Cell Width
Cell_H = int(Window_Height / Cell_Size)  # Cell Height

White = (255, 255, 255)
Black = (0, 0, 0)
Red = (255, 0, 0)  # Defining element colors for the program.
Green = (0, 255, 0)
DARKGreen = (0, 155, 0)
DARKGRAY = (40, 40, 40)
YELLOW = (255, 255, 0)
Red_DARK = (150, 0, 0)
BLUE = (0, 0, 255)
BLUE_DARK = (0, 0, 150)

BGCOLOR = Black  # Background color

UP = 'up'
DOWN = 'down'  # Defining keyboard keys.
LEFT = 'left'
RIGHT = 'right'

HEAD = 0  # Syntactic sugar: index of the snake's head


def main():
    global SnakespeedCLOCK, DISPLAYSURF, BASICFONT

    pygame.init()
    SnakespeedCLOCK = pygame.time.Clock()
    DISPLAYSURF = pygame.display.set_mode((Window_Width, Window_Height))
    BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
    pygame.display.set_caption('Snake')

    showStartScreen()
    while True:
        runGame()
        showGameOverScreen()


def runGame():
    # Set a random start point.
    startx = random.randint(5, Cell_W - 6)
    starty = random.randint(5, Cell_H - 6)
    wormCoords = [{'x': startx, 'y': starty},
                {'x': startx - 1, 'y': starty},
                {'x': startx - 2, 'y': starty}]
    direction = RIGHT

    # Start the apple in a random place.
    apple = getRandomLocation()

    while True:  # main game loop
        for event in pygame.event.get():  # event handling loop
            if event.type == QUIT:
                terminate()
            elif event.type == KEYDOWN:
                if (event.key == K_LEFT) and direction != RIGHT:
                    direction = LEFT
                elif (event.key == K_RIGHT) and direction != LEFT:
                    direction = RIGHT
                elif (event.key == K_UP) and direction != DOWN:
                    direction = UP
                elif (event.key == K_DOWN) and direction != UP:
                    direction = DOWN
                elif event.key == K_ESCAPE:
                    terminate()

        # check if the Snake has hit itself or the edge
        if wormCoords[HEAD]['x'] == -1 or wormCoords[HEAD]['x'] == Cell_W or wormCoords[HEAD]['y'] == -1 or \
                wormCoords[HEAD]['y'] == Cell_H:
            return  # game over
        for wormBody in wormCoords[1:]:
            if wormBody['x'] == wormCoords[HEAD]['x'] and wormBody['y'] == wormCoords[HEAD]['y']:
                return  # game over

        # check if Snake has eaten an apply
        if wormCoords[HEAD]['x'] == apple['x'] and wormCoords[HEAD]['y'] == apple['y']:
            # don't remove worm's tail segment
            apple = getRandomLocation()  # set a new apple somewhere
        else:
            del wormCoords[-1]  # remove worm's tail segment

        # move the worm by adding a segment in the direction it is moving
        if direction == UP:
            newHead = {'x': wormCoords[HEAD]['x'],
                'y': wormCoords[HEAD]['y'] - 1}
        elif direction == DOWN:
            newHead = {'x': wormCoords[HEAD]['x'],
                'y': wormCoords[HEAD]['y'] + 1}
        elif direction == LEFT:
            newHead = {'x': wormCoords[HEAD][
                                'x'] - 1, 'y': wormCoords[HEAD]['y']}
        elif direction == RIGHT:
            newHead = {'x': wormCoords[HEAD][
                                'x'] + 1, 'y': wormCoords[HEAD]['y']}
        wormCoords.insert(0, newHead)
        DISPLAYSURF.fill(BGCOLOR)
        drawGrid()
        drawWorm(wormCoords)
        drawApple(apple)
        drawScore(len(wormCoords) - 3)
        pygame.display.update()
        SnakespeedCLOCK.tick(Snakespeed)


def drawPressKeyMsg():
    pressKeySurf = BASICFONT.render('Press a key to play.', True, White)
    pressKeyRect = pressKeySurf.get_rect()
    pressKeyRect.topleft = (Window_Width - 200, Window_Height - 30)
    DISPLAYSURF.blit(pressKeySurf, pressKeyRect)


def checkForKeyPress():
    if len(pygame.event.get(QUIT)) > 0:
        terminate()
    keyUpEvents = pygame.event.get(KEYUP)
    if len(keyUpEvents) == 0:
        return None
    if keyUpEvents[0].key == K_ESCAPE:
        terminate()
    return keyUpEvents[0].key


def showStartScreen():
    titleFont = pygame.font.Font('freesansbold.ttf', 100)
    titleSurf1 = titleFont.render('Snake!', True, White, DARKGreen)
    degrees1 = 0
    degrees2 = 0
    while True:
        DISPLAYSURF.fill(BGCOLOR)
        rotatedSurf1 = pygame.transform.rotate(titleSurf1, degrees1)
        rotatedRect1 = rotatedSurf1.get_rect()
        rotatedRect1.center = (Window_Width / 2, Window_Height / 2)
        DISPLAYSURF.blit(rotatedSurf1, rotatedRect1)

        drawPressKeyMsg()

        if checkForKeyPress():
            pygame.event.get()  # clear event queue
            return
        pygame.display.update()
        SnakespeedCLOCK.tick(Snakespeed)
        degrees1 += 3  # rotate by 3 degrees each frame
        degrees2 += 7  # rotate by 7 degrees each frame


def terminate():
    pygame.quit()
    sys.exit()


def getRandomLocation():
    return {'x': random.randint(0, Cell_W - 1), 'y': random.randint(0, Cell_H - 1)}


def showGameOverScreen():
    gameOverFont = pygame.font.Font('freesansbold.ttf', 100)
    gameSurf = gameOverFont.render('Game', True, White)
    overSurf = gameOverFont.render('Over', True, White)
    gameRect = gameSurf.get_rect()
    overRect = overSurf.get_rect()
    gameRect.midtop = (Window_Width / 2, 10)
    overRect.midtop = (Window_Width / 2, gameRect.height + 10 + 25)

    DISPLAYSURF.blit(gameSurf, gameRect)
    DISPLAYSURF.blit(overSurf, overRect)
    drawPressKeyMsg()
    pygame.display.update()
    pygame.time.wait(500)
    checkForKeyPress()  # clear out any key presses in the event queue

    while True:
        if checkForKeyPress():
            pygame.event.get()  # clear event queue
            return


def drawScore(score):
    scoreSurf = BASICFONT.render('Score: %s' % (score), True, White)
    scoreRect = scoreSurf.get_rect()
    scoreRect.topleft = (Window_Width - 120, 10)
    DISPLAYSURF.blit(scoreSurf, scoreRect)


def drawWorm(wormCoords):
    for coord in wormCoords:
        x = coord['x'] * Cell_Size
        y = coord['y'] * Cell_Size
        wormSegmentRect = pygame.Rect(x, y, Cell_Size, Cell_Size)
        pygame.draw.rect(DISPLAYSURF, DARKGreen, wormSegmentRect)
        wormInnerSegmentRect = pygame.Rect(
            x + 4, y + 4, Cell_Size - 8, Cell_Size - 8)
        pygame.draw.rect(DISPLAYSURF, Green, wormInnerSegmentRect)


def drawApple(coord):
    x = coord['x'] * Cell_Size

    y = coord['y'] * Cell_Size
    appleRect = pygame.Rect(x, y, Cell_Size, Cell_Size)
    pygame.draw.rect(DISPLAYSURF, Red, appleRect)


def drawGrid():
    for x in range(0, Window_Width, Cell_Size):  # draw vertical lines
        pygame.draw.line(DISPLAYSURF, DARKGRAY, (x, 0), (x, Window_Height))
    for y in range(0, Window_Height, Cell_Size):  # draw horizontal lines
        pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, y), (Window_Width, y))


if __name__ == '__main__':
    try:
        main()
    except SystemExit:
        pass

最后感谢粉丝们的支持和鼓励!

祝粉丝们天天开心,万事如意,意气风发,发奋图强!

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值