Python cool special effects code is simple, cool animation made by python

This article tells you about the simple code of python's cool special effects and the nice pattern code of python. I hope it will be helpful to you. Don't forget to bookmark this site.

1. How to use Python to make a fun and cool GIF dynamic map

import sys
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()
fig.set_tight_layout(True)

# Ask about the size and DPI (dots per inch) of the graphic on the screen
# Note that when saving the graphics as a file, you need to provide a separate DPI for this
print('fig size: {0} DPI, size in inches {1}'.format(
 fig.get_dpi(), fig.get_size_inches()))

# Draw a scatterplot that stays the same (will not be redrawn) and the initial line
x = np.arange(0, 20, 0.1)
ax.scatter(x, x + np.random.normal(0, 3.0, len(x)))
line, = (x, x - 5, 'r-', linewidth=2)

def 携腊update(i):
 label = 'timestep {0}'.format(i)
 print(label)
# update the line and axes (with a new x-axis label)
 # Return the objects that need to be redrawn in this frame as a tuple
 line.set_ydata(x - 5 + i)
 ax.set_xlabel(label)
 return line, ax

if __name__ == '__main__':
 # will call the Update function for each frame
 # Here FunAnimation sets a 10-frame animation with an interval of 200ms between each frame
 anim = FuncAnimation(fig, update, frames=np.arange(0, 10), interval=200)
 if len() > 1 and [1] == pure implicit 'save':
  ('', dpi=80, writer='imagemagick')
 else:
  # () will keep looping the animation
  ()

The following graph can be generated

2. Python language, use recursion to draw colored fourth-order pentagonal Koch snowflakes, and upload the code and Koch snowflake renderings?

import random

import turtle

def random_color():

    rgbl=[255,0,0]

    random.shuffle(rgbl)

    return tuple(rgbl)

def koch(size,n):

    if n==0:

        (size)

    else:

        for angle in [0,60,-120,60]:

            cc = random_color()

            turtle.pencolor(cc[0], cc[1], cc[2])

            (angle)

     Lian Zhi Li builds a hole koch(size/3,n-1)

def main():

    turtle.colormode(255)

    turtle.setup(600,600)

    turtle.penup()

    (-200,100)

    turtle. pendown()

    turtle.pensize(2)

    level=4 #4th order Koch snowflake, order

    koch(400,level)

    turtle.right(120)

    koch(400,level)

    turtle.right(120)

    koch(400,level)

    turtle.hideturtle()

    ()

main()

The effect is as shown in the search diagram:

3. Rock-paper-scissors python programming code

  • player = int(input("Please punch stone (1)/scissors (2)/cloth (3)"))

  • computer = 1

  • if((player == 1 and computer == 2) or

  • (player == 2 and computer == 3) or

  • (player == 3 and computer == 1)):

  • print("Oye! The waiter and the computer are so weak!")

  • elif player == computer:

  • print("There is a consonance in the heartbeat, let's have another game!")

  • else:

  • print("No, I want to fight with you until dawn!")

When executing, the first line must be copied separately, because you need to enter a value

4, python color python code

There is a drawing library called turtle in Python, let's introduce it first. importturtle (python uses import or from...import to import corresponding modules, which is similar to the include header file in C, please refer to the specific usage of rubber clap import) and turtle is a drawing library. Here I will only introduce a few commonly used ones. Function
turtle.setup (a, b, c, d) a, b two parameters control the width and height of the canvas, c, d properties control the position of the canvas; turtle.screesize (a, b, c) a, b control The width and height of the canvas, C controls the color of the canvas; for example: turtle.setup(800,400,200,200)//Create a canvas with a width of 800 pixels and a height of 400 pixels, and the coordinates are (200,200) Liang Sixian turtle.screensize(800,400,' green')//Create a hail pie canvas with a width of 800 pixels, a height of 400 pixels, and a color of green

5. Python code for drawing love

I've tried my best, but it might be a bit difficult to make a really good looking heart (except for the textures, but that's not good after all, right).

The following is the Python code:

from turtle import *

speed(0)#speed, if you think it is too fast, you can adjust it to 1 (1 is slow, 10 is fast, 0 is the fastest)

tracer(2)#Display the speed, if you think it is too fast, you can adjust it to 1 (same as above)

hideturtle()#Hide the brush

setup(500,500)#500×500 square screen

up()#lift the pen

goto(-150,50)#go to the target point

down()# pen down

color("red","red")#The brush is filled with red

seth(90)# change the direction to Celery

begin_fill()#start filling

circle(-75,180)#Draw a semicircle to the right

circle(75,-180)#Draw a semicircle to the right

step = 4.06635

seth(270)#down

for i in range(90):#画卷想恩羽圆

    forward(step)# walk step length

    step = step - 0.025# gradually reduce the step size

    right(1)# turn right 1 degree

for i in range(90):

    step = step + 0.025# gradually increase the step size

    right(1)# turn right 1 degree

    forward(step)# walk step length

end_fill()


The following is the running effect:

a heart

6. Python interesting programming code

class Point:
  row=0
  col=0
  def __init__(self, row, col):
    =row
 Changhu socks =col

  def copy(self):
    return Point(, )


#initial frame
import pygame
import random

#initialization
()
W=800
H=600

ROW=30
COL=40

size=(W,H)
window=pygame.display.set_mode(size)
pygame.display.set_caption('')

bg_color=(255,255,255)
snake_color=(200,200,200)

head=Point(row=int(ROW/2), col=int(COL/2))
head_color=(0,128,128)

snakes=[
  Point(, +1),
  Point(, +2),
  Point(, +3)
]

# generate food
def gen_food():
  while 1:
    pos=Point(row=random.randint(0,ROW-1), col=random.randint(0,COL-1))

    #
    is_coll=False

    Endurance#Is there a snake
    if  and :
      is_coll=True

    #snake body
    for snake in snakes:
      if  and :
        is_coll=True
        break

    if not is_coll:
      break

  return pos


#define coordinates


food=gen_food()
food_color=(255,255,0)



direct='left'       #left,right,up,down

#
def rect(point, color):
  cell_width=W/COL
  cell_height=H/ROW

  *cell_width
 Qingfan *cell_height

  (
    window, color,
    (left, top, cell_width, cell_height)
  )
  pass

#game loop
quit=True
.Clock()
while quit:
  #handle events
  for event in ():
    if :
      quit=False
    elif ==pygame.KEYDOWN:
      if ==273 or ==119:
        if direct=='left' or direct=='right':
          direct='up'
      elif ==274 or ==115:
        if direct == 'left' or direct == 'right':
          direct='down'
      elif ==276 or ==97:
        if direct == 'up' or direct == 'down':
          direct='left'
      elif ==275 or ==100:
        if direct == 'up' or direct == 'down':
          direct='right'

  #eat
  eat=( and )

  #regenerate food
  if eat:
    food = gen_food()

  #handle the body
  #1. Insert the original head into the head of snakes
  snakes.insert(0, ())
  #2. Delete the last one of snakes
  if not eat:
    ()

  #move
  if direct=='left':
    -=1
  elif direct=='right':
    +=1
  elif direct=='up':
    -=1
  elif direct=='down':
    +=1

  # detection
  dead=False
  #1. Hit the wall
  if <0 or <0 or >=COL or >=ROW:
    dead=True

  #2. Bump yourself
  for snake in snakes:
    if  and :
      dead=True
      break

  if dead:
    print('dead')
    quit=False

  #rendering - draw it
  #background
  (window, bg_color, (0,0,W,H))

  #snakehead
  for snake in snakes:
    rect(snake, snake_color)
  rect(head, head_color)
  rect(food, food_color)

  #
  ()

  #Set the frame rate (speed)
  (8)

#finishing work

This is a simple version of Snake code. Although the structure is simple, all the necessary functions are complete and the playability is good.

Guess you like

Origin blog.csdn.net/chatgpt001/article/details/131938161