少儿编程-聂士翔

这个博客展示了使用Python编程实现的各种游戏,包括机器猫脸部绘制、DIY计算器、移动的波点、跳动的星星、贪吃蛇游戏、挡板与小球碰撞以及弹弹球游戏。通过这些游戏,可以学习到Python的基础语法、图形界面交互以及游戏逻辑的实现。
摘要由CSDN通过智能技术生成

cls29 -机器猫

import turtle
p = turtle.Pen()
def face():
    p.fillcolor("blue")
    p.begin_fill()
    p.circle(100)
    p.end_fill()
    p.fillcolor("white")
    p.begin_fill()
    p.circle(80)
    p.end_fill()

def eye():
    p.penup()
    p.goto(0,160)
    p.pendown()
    p.left(90)
    p.fillcolor("white")
    p.begin_fill()
    p.circle(20)
    p.end_fill()
    p.fillcolor("black")
    p.begin_fill()
    p.circle(5)
    p.end_fill()
    



face()
eye()
turtle.done()

cls29 DIY计算器

a = input("请输入一串算式")
def isNum(c):
    if c not in "+-*/":
        return True
    return False
def splitCal(content):
    lst = []
    lst2 = []
    index_last = 0
    index_current = 0
    for i in range(len(content)):
        index_current = i
        if isNum(content[i]):
            if index_current ==len(content)-1:
                lst.append(float(content[index_last:]))
            else:
                pass
        else:
            lst2.append(content[index_current])
            lst.append(float(content[index_last:index_current]))
            index_last = index_current+1
    return lst,lst2

def cal(a,op,b):
    if op == "+":
        return a+b
    elif op == "-":
        return a-b
    elif op == "*":
        return a*b
    else:
        return a/b

def calculator(content):
    islst,arelst = splitCal(content)
    print(islst)
    print(arelst)
    i = 0
    while i < len(arelst):
        if arelst[i] in "*/":
            islst[i] = cal(islst[i],arelst[i],islst[i + 1])
            del arelst[i]
            del islst[i + 1]
        else:
            i += 1
    i=0
    while i < len(arelst):
        islst[i] = cal(islst[i], arelst[i], islst[i + 1])
        del arelst[i]
        del islst[i + 1]
    return islst[0]

result = calculator(a)
print(result)


画板

import turtle
lst = [(280,220),(280,180),(280,140),(280,100)]
color_lst = ["red","orange","yellow","green"]
r = 30
p = turtle.Pen()


def draw_color_board(pen,lst,color_lst,radius):
    pen.penup()
    pen.goto(300,60)
    pen.pendown()
    pen.seth(90)
    pen.forward(200)
    pen.left(90)
    pen.forward(40)
    pen.left(90)
    pen.forward(200)
    pen.left(90)
    pen.forward(40)
    for i in range(len(color_lst)):
        pen.penup()
        pen.goto(lst[i])
        pen.pendown()
        pen.pencolor(color_lst[i])
        pen.dot(radius)




def up():
    p.sety(p.ycor() + 10)


def down():
    p.sety(p.ycor() - 10)


def left():
    p.setx(p.xcor() - 10)


def right():
    p.setx(p.xcor() + 10)


def week_y(x,y):
    p.goto(x,y)
    for i in range(4):
        if (x-lst[i][0])**2+(y-lst[i][1])**2 <= 900:
            p.pencolor(color_lst[i])
            break





draw_color_board(p,lst,color_lst,r)
p.penup()
p.home()
p.pendown()
turtle.onscreenclick(week_y)
turtle.onkeypress(up, "Up")
turtle.onkeypress(down, "Down")
turtle.onkeypress(left, "Left")
turtle.onkeypress(right, "Right")
turtle.listen()
turtle.done()

知识问答

import turtle,time
question_lst = []
answer_lst = []
option_lst = []
position_lst = []
question_pen = turtle.Pen()
result_pen = turtle.Pen()
question_index = 0


def init():
    global question_lst,answer_lst,option_lst,position_lst,question_index,question_pen,result_pen
    turtle.bgpic('背景.png')
    turtle.setup(720,720)
    question_lst = ['[整数在python中是怎么表示的]',
                    '[怎样在python中输出]',
                    '[条件判断在python中是怎么写的]']
    answer_lst = ['int','print','if']
    option_lst = [['A.int','B.float,','C.str'],
                  ['A.while','B.print','C.input'],
                  ['A.if','B.lst','C.turtle']]
    position_lst = [[-180,-100],[0,-100],[200,-100]]
    question_index = 0
    question_pen = turtle.Pen()
    question_pen.hideturtle()
    result_pen = turtle.Pen()
    result_pen.hideturtle()
    result_pen.penup()
    result_pen.goto(-100,-50)


def word(p,color,text,size=30):
    p.pencolor(color)
    p.write(text,font=("Arial",size))


def question(p,q_lst,o_lst,p_lst,index):
    p.clear()
    p.penup()
    p.goto(-300,150)
    p.pendown()
    if index >= len(q_lst):
        p.penup()
        p.goto(-50,0)
        p.pendown()
        word(p,"green","已通关")
        return
    word(p,"black",q_lst[index],30)
    for i in range(3):
        p.penup()
        p.goto(p_lst[i][0] - 55,p_lst[i][1] + 25)
        p.pendown()
        word(p,"black",o_lst[index][i],size=20)

def checkPos(x,y):
    global question_index


    for i in range(len(option_lst)):
        if position_lst[i][0] - 80 < x < position_lst[i][0]+30 and position_lst[i][1]  < y < position_lst[i][1] + 80:
            if option_lst[question_index][i].split('.')[1] == answer_lst[question_index]:
                question_index += 1
                result(result_pen,'right',x,y)
                question(question_pen,question_lst,option_lst,position_lst,question_index)
            else:
                result(result_pen,'wrong',x,y)


def result(p,r,x,y):
    p.goto(x,y)
    if r == 'right':
        word(p,'green','恭喜你回答正确',30)
    else:
        word(p,'red','再想想哦',30)
    time.sleep(1)
    p.clear()



init()
turtle.onscreenclick(checkPos)
turtle.tracer(0)
question(question_pen,question_lst,option_lst,position_lst,question_index)
turtle.done()


在这里插入图片描述

移动的波点

import turtle,random
p = turtle.Pen()
turtle.setup(530,500)
dot_pos = [[0,-60],[200,0],[250,50]]

turtle.tracer(False)
def draw(pos_lst):

    p.clear()
    for i in pos_lst:
        p.penup()
        p.goto(i)
        p.pendown()
        p.dot(40)


def move():
    global dot_pos,a
    for i in dot_pos:
        i[0] -= 20
        if i[0] <= -200:
            dot_pos.remove(i)
            dot_pos.append([265,random.randint(-240,240)])



def process():

    draw(dot_pos)
    move()
    turtle.ontimer(process,1000)

process()
turtle.done()

跳动的星星

import turtle

p = turtle.Pen()
p.pencolor("green")
x_y = [[-150, 0], [-100, 60], [40, 30], [230, 10]]
turtle.tracer(False)
a = -1

def dot_dot():
    p.clear()
    for i in range(4):
        p.penup()
        p.goto(x_y[i])
        p.pendown()
        p.dot(50)


def run():
    global x_y
    for i in x_y:
        i[1] -= 3


def process():
    dot_dot()
    run()
    turtle.ontimer(process,100)


def jump(x,y):
    global x_y
    for i in x_y:
        if (i[0]-x)**2+(i[1]-y)**2<=25**2:
            x_y.remove(i)




process()
turtle.onscreenclick(jump)
turtle.done()

星星和波点碰撞

p = turtle.Pen()
t = turtle.Pen()
w = turtle.Pen()
turtle.tracer(False)
color = ["green", "blue", "red"]
x_y = [[-20, 50], [-10, 120], [30, 100], [-50,40], [180, -40]]
x_y1 = [[0, 400]]
running = True
score_number = 0


def red_dot(p):
    global x_y
    p.pencolor(color[2])
    p.clear()
    for i in x_y:
        p.penup()
        p.goto(i)
        p.pendown()
        p.dot(30)
    # for j in range(len(x_y)):
    #     x_y[j][0] += 20
    #     if x_y[j][0] >= 400:
    #         x_y.remove(x_y[j])
    #         temp = [random.randint(-400,400),random.randint(-300,300)]
    #         x_y.insert(j,temp)
    j = 0
    while j <= len(x_y)-1:
        x_y[j][0] += 20
        if x_y[j][0] >= 400:
            x_y.remove(x_y[j])
            temp = [-400, random.randint(-300, 300)]
            x_y.append(temp)
            j -= 1
        j += 1



def green_stars(p):
    global x_y1
    p.pencolor(color[0])
    p.clear()
    for i in x_y1:
        p.fillcolor(color[0])
        p.penup()
        p.goto(i)
        p.setheading(162)
        p.forward(math.atan(18)*15)
        p.pendown()
        p.setheading(0)
        p.begin_fill()
        p.forward(30)
        p.right(144)
        p.forward(30)
        p.right(144)
        p.forward(30)
        p.right(144)
        p.forward(30)
        p.right(144)
        p.forward(30)
        p.right(144)
        p.end_fill()
    x_y1[0][1] -= 10
    if x_y1[0][1] < -400:
        x_y1[0][1] = 400
        scure()

def collision():
    global running
    for i in range(len(x_y)):
        if (x_y1[0][0] - x_y[i][0]) ** 2 + (x_y1[0][1] - x_y[i][1]) ** 2 < 900:
            running = False
            break



def run():
    red_dot(p)
    green_stars(t)
    collision()
    if running:
        turtle.ontimer(run, 100)



def jump(x,y):
    x_y1[0][1] += 100


def scure():
    global score_number
    score_number += 1
    w.clear()
    w.write(score_number,font=("arial",30,"bold"))

run()
turtle.onscreenclick(jump)
turtle.done()

贪吃蛇

import turtle
p = turtle.Pen()
x_y = [[0,0]]
turtle.tracer(False)
direction = "down"
size = (800,600)
turtle.setup(size[0],size[1])

def snake():
    global x_y
    p.pencolor("red")
    p.clear()

    for i in x_y:
        p.penup()
        p.goto(i)
        p.pendown()
        p.dot(30)


def move():
    for j in x_y:
        if direction == "up":
            j[1] += 20
            if j[1] > size[1] / 2:
                j[1] = -size[1] / 2
        if direction == "down":
            j[1] -= 20
            if j[1] < -size[1] / 2:
                j[1] = size[1] / 2
        if direction == "left":
            j[0] -= 20
            if j[0] < -size[0] / 2:
                j[0] = size[0] / 2
        if direction == "right":
            j[0] += 20
            if j[0] > size[0] / 2:
                j[0] = -size[0] / 2

def running():
    snake()
    move()
    turtle.ontimer(running,100)


def onUpClick():
    global direction
    direction = "up"


def onDownClick():
    global direction
    direction = "down"


def onLeftClick():
    global direction
    direction = "left"


def onRightClick():
    global direction
    direction = "right"

turtle.onkeypress(onUpClick,"Up")
turtle.onkeypress(onDownClick,"Down")
turtle.onkeypress(onLeftClick,"Left")
turtle.onkeypress(onRightClick,"Right")
turtle.listen()
running()
turtle.done()



贪吃蛇

import turtle,random

p = turtle.Pen()
t = turtle.Pen()
food = [40,20]
x_y = [[0,0],[20,0]]
turtle.tracer(False)
direction = "down"
size = (800,600)

turtle.setup(size[0],size[1])


def snake_food(p):
    p.clear()
    p.pencolor("green")
    p.penup()
    p.goto(food[0],food[1])
    p.pendown()
    p.dot(20)


def snake():
    global x_y
    p.pencolor("red")
    p.clear()

    for i in x_y:
        p.penup()
        p.goto(i)
        p.pendown()
        p.dot(20)


def move():
    length = len(x_y)
    for i in range(length-1):
        x_y[length-1-i] = x_y[length-2-i].copy()

    if direction == "up":
        x_y[0][1] += 20
        if x_y[0][1] > size[1] / 2:
            x_y[0][1] = -size[1] / 2
    if direction == "down":
        x_y[0][1] -= 20
        if x_y[0][1] < -size[1] / 2:
            x_y[0][1] = size[1] / 2
    if direction == "left":
        x_y[0][0] -= 20
        if x_y[0][0] < -size[0] / 2:
            x_y[0][0] = size[0] / 2
    if direction == "right":
        x_y[0][0] += 20
        if x_y[0][0] > size[0] / 2:
            x_y[0][0] = -size[0] / 2


def running():
    snake()
    move()
    snake_food(t)
    collide()
    turtle.ontimer(running,100)


def onUpClick():
    global direction
    direction = "up"


def onDownClick():
    global direction
    direction = "down"


def onLeftClick():
    global direction
    direction = "left"


def onRightClick():
    global direction
    direction = "right"


def collide():
    global food
    if (x_y[0][0] - food[0]) ** 2 + (x_y[0][1] - food[1]) **2 <= 900:
        food = [random.randint(-350,350),random.randint(-250,250)]
        x_y.append(x_y[-1].copy())


turtle.onkeypress(onUpClick,"Up")
turtle.onkeypress(onDownClick,"Down")
turtle.onkeypress(onLeftClick,"Left")
turtle.onkeypress(onRightClick,"Right")
turtle.listen()
running()
turtle.done()



贪吃蛇

import turtle,random
#定义两个画笔
p = turtle.Pen()
t = turtle.Pen()
#变量控制方向
direct = "up"
#设置画布大小
turtle.setup(800,800)
#食物和蛇身初始坐标
food = [30,0]
index = [[0,0],[0,-20],[0,-40]]
#关闭动画效果
turtle.tracer(False)
game = True
step_size = 20

#函数画蛇
def draw_snake():
    p.clear()
    for i in range(len(index)):
        p.penup()
        p.goto(index[i])
        p.pendown()
        p.dot(20,"red")


#函数画蛇的食物
def snake_food(p):
    p.clear()
    p.pencolor("green")
    p.penup()
    p.goto(food[0], food[1])
    p.pendown()
    p.dot(20)


#四个函数控制方向
def up_snake():
    global direct
    if direct != "down":
        direct = "up"


def down_snake():
    global direct
    if direct != "up":
        direct = "down"


def left_snake():
    global direct
    if direct != "right":
        direct = "left"


def right_snake():
    global direct
    if direct != "left":
        direct = "right"


#控制蛇移动
def move_snake():
    a = index[0].copy()
    if direct == "up":
        a[1] += step_size
    elif direct == "down":
        a[1] -= step_size
    elif direct == "left":
        a[0] -= step_size
    elif direct == "right":
        a[0] += step_size
    #改变蛇的位置,让它动起来
    index.insert(0, a)
    #删除做后一个坐标
    index.pop()
#超出画布从对应边出现
    if a[0] > 400:
        a[0] = -400
    if a[0] < -400:
        a[0] = 400
    if a[1] > 400:
        a[1] = -400
    if a[1] < -400:
        a[1] = 400


#点击鼠标增加蛇身
def Append(x,y):
    index.append(index[-1])


def collide_die():
    global game
    for i in range(1,len(index)):
        size = (index[0][0] - index[i][0]) **2 + (index[0][1] - index[i][1]) ** 2
        if size < 400:
            game = False
            break

#吃食物碰撞消失,增加蛇的长度
def collide():
    global food
    if (index[0][0] - food[0]) ** 2 + (index[0][1] - food[1]) ** 2 <= 900:
        food = [random.randint(-350, 350), random.randint(-250, 250)]
        index.append(index[-1].copy())


def start():
    global food,index,game
    if game == True:
        return
    else:
        food = [30, 0]
        index = [[0, 0], [0, -20], [0, -40]]
        game = True
        process()

#驱动,同时调用
def process():
    global game
    if game == True:
        draw_snake()
        move_snake()
        snake_food(t)
        collide()
        collide_die()
        turtle.ontimer(process,100)


#监听按键
turtle.onkeypress(up_snake,"Up")
turtle.onkeypress(down_snake,"Down")
turtle.onkeypress(left_snake,"Left")
turtle.onkeypress(right_snake,"Right")
turtle.onscreenclick(Append)
turtle.onkeypress(start,"space")
turtle.listen()

process()

turtle.done()



挡板和小球

import turtle
turtle.setup(800, 800)
# 游戏状态
game_state = True
# 游戏结果
game_result = "red"
# 小球的坐标
ball = [0,0]
# 小球的移动步子大小
ball_move_s = [-1,3]
# 小球大小
ball_size = 20
# 挡板的坐标
blue_board = [-375,0]
red_board = [375,0]
turtle.tracer(False)
# 挡板的尺寸
board_width,board_height = 20,100
p1 = turtle.Pen()
p2 = turtle.Pen()
p3 = turtle.Pen()
# 每次移动的大小
step_size = 20
def draw_board(p,color,index):
    p.clear()
    p.pensize(1)
    p.pencolor(color)
    p.fillcolor(color)
    p.begin_fill()
    p.penup()
    p.goto(index[0]+board_width/2,index[1])
    p.pendown()
    p.setheading(-90)
    p.forward(board_height/2)
    p.right(90)
    p.forward(board_width)
    p.right(90)
    p.forward(board_height)
    p.right(90)
    p.forward(board_width)
    p.right(90)
    p.forward(board_height/2)
    p.end_fill()


def draw_ball(p):
    p.clear()
    p.penup()
    p.goto(ball)
    p.pendown()
    p.pencolor("black")
    p.dot(ball_size)


def move_ball():
    global ball,ball_move_s,game_state,game_result
    ball[0] += ball_move_s[0]
    ball[1] += ball_move_s[1]
    if ball[1] >= 400 or ball[1]<=-400:
        ball_move_s[1] = -ball_move_s[1]

    # 球是否撞击到板子上
    if ball[0]<=blue_board[0]+board_width/2+ball_size/2:
        if blue_board[1]-board_height/2<=ball[1]<=blue_board[1]+board_height/2:
            ball_move_s[0] = -ball_move_s[0]

    if ball[0] >= red_board[0] - board_width/2 - ball_size/2:
        if red_board[1] - board_height / 2 <= ball[1] <= red_board[1] + board_height / 2:
            ball_move_s[0] = -ball_move_s[0]

    # 出界判断
    if ball[0] <= blue_board[0]:
        game_state = False
        game_result = "red"
    elif ball[0] >= red_board[0]:
        game_state = False
        game_result = "blue"




def move(player,value,action):
    global blue_board,red_board
    if player == "player_1":
        if action == "w":
            blue_board[1]+=value
        elif action == "s":
            blue_board[1] -= value
    elif player == "player_2":
        if action == "up":
            red_board[1] += value
        elif action == "down":
            red_board[1] -= value


def process():
    if True:
        draw_board(p1,"blue", blue_board)
        draw_board(p2,"red", red_board)
        draw_ball(p3)
        move_ball()
        turtle.ontimer(process,10)
    else:
        p1.clear()
        p2.clear()
        p3.clear()
        turtle.write("游戏结束,{}赢了".format(game_result))

turtle.onkeypress(lambda :move("player_1",step_size,"w"),"w")
turtle.onkeypress(lambda :move("player_1",step_size,"s"),"s")
turtle.onkeypress(lambda :move("player_2",step_size,"up"),"Up")
turtle.onkeypress(lambda :move("player_2",step_size,"down"),"Down")
turtle.listen()
process()
turtle.done()


弹弹球

import pygame,random   # 事件

pygame.init()
pygame.key.set_repeat(50,50)
s_width = 500
s_height = 500
screen = pygame.display.set_mode((s_width,s_height))
# 角色的位置
ball_pos = [200,400]
b_m_size = [1,1]
rect_pos = [200,450]
red_pos_lst=[]

# 小球 板子 红球组对象
black_ball = None
black_board = None
red_balls = []
# 小球移动的频率
b_m_fre = 0
# 游戏停止
stop = []

def draw_all():
    """
    绘制屏幕上所有的图案
    :return:None
    """
    global black_ball,black_board
    red_balls.clear()
    black_ball = pygame.draw.circle(screen, (0, 0, 0), ball_pos, 5, 0)
    black_board = pygame.draw.rect(screen,(0,0,0),rect_pos+[100,20])
    for i in range(len(red_pos_lst)):
        temp = pygame.draw.circle(screen,(255,0,0),red_pos_lst[i],5,0)
        red_balls.append(temp)


def ball_move():
    """
    黑球和板子碰撞检测
    黑球和红球组碰撞检测
    :return:
    """
    global ball_pos,b_m_size,b_m_fre
    b_m_fre += 1
    if b_m_fre<=1:
        return
    b_m_fre = 1
    ball_pos[0] += b_m_size[0]
    ball_pos[1] += b_m_size[1]

    if ball_pos[0] >=s_width:
        b_m_size[0] = random.choice([-1,-2])
    if ball_pos[0] <=0:
        b_m_size[0] = random.choice([1, 2])

    if ball_pos[1] >=s_height:
        b_m_size[1] = random.choice([-1,-2])
    if ball_pos[1] <=0:
        b_m_size[1] = random.choice([1, 2])



def board_move(action):
    global rect_pos
    if action == 1:
        rect_pos[0] += 10
        if rect_pos[0]+100 >=s_width:
            rect_pos[0] = s_width-100

    else:
        rect_pos[0] -= 10
        if rect_pos[0] <=0:
            rect_pos[0] = 0


def collide_all():
    """
    测试
    板子和小黑球是否碰撞
    :return:
    """
    global black_board,black_ball,b_m_size,ball_pos,rect_pos
    result = black_board.colliderect(black_ball)
    if result:
        if ball_pos[1] <= rect_pos[1]:
            b_m_size[1] = random.choice([-1, -2])
        elif ball_pos[1] >= rect_pos[1]+20:
            b_m_size[1] = random.choice([1, 2])

        if ball_pos[0]<=rect_pos[0]:
            b_m_size[0] = random.choice([-1,-2])
        elif ball_pos[0]>=rect_pos[0]+100:
            b_m_size[0] = random.choice([1, 2])
    # 黑球和红球组碰撞检测
    index = black_ball.collidelist(red_balls)
    if index != -1:
        if black_ball[0] < red_pos_lst[index][0]:
            b_m_size[0] = random.choice([-1, -2])
        elif black_ball[0] > red_pos_lst[index][0]:
            b_m_size[0] = random.choice([1, 2])

        if black_ball[1] < red_pos_lst[index][1]:
            b_m_size[1] = random.choice([-1, -2])
        elif black_ball[1] > red_pos_lst[index][1]:
            b_m_size[1] = random.choice([1, 2])

        red_pos_lst.pop(index)

def create_redballs():
    global red_pos_lst
    for i in range(0,50):
        for j in range(0,30):
            red_pos_lst.append([5+i*10,5+j*10])

    for i in range(20,30):
        for j in range(0,30):
            red_pos_lst.remove([5 + i * 10, 5 + j * 10])



create_redballs()
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                board_move(0)
            if event.key == pygame.K_RIGHT:
                board_move(1)

    # 游戏停止
    if red_pos_lst == stop:
        pass
    else:
        screen.fill((255,255,255))
        draw_all()
        ball_move()
        collide_all()

    pygame.display.update()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值