用turtle做游戏

turtle居然还能做游戏?当然能,turtle能做贪吃蛇、推箱子等游戏,由于篇幅过长,这里只展示视频链接:https://www.bilibili.com/video/BV1pa4y1D7tU/?spm_id_from=333.788

以上链接是blibli里 灰灰讲编程 里的

以下代码是一个较为完整的贪吃蛇代码(至少可以玩起来像样)

1、snake.py 文件代码(主文件):

import turtle
import random
from settings import *
from tools import draw_rect

def init():
    turtle.tracer(0)
    turtle.hideturtle()
    turtle.up()
    turtle.setup(w,h)
    turtle.title("贪吃蛇游戏")

def draw_bg():
    for row in range(row_num):
        for col in range(col_num):
            turtle.goto(tx+col*s,ty-row*s)
            c = colors['bg'][row%2==col%2]
            draw_rect(s,c,c)

def draw_tips():
    turtle.goto(tx, ty)
    turtle.color(colors['font'])
    turtle.write('得分: ' + str(score), 0,'left',('楷体',12,'normal')) # type: ignore
    if status == 0:
        turtle.goto(0,0)
        turtle.write('Game Over',0,'center',('楷体',80,'normal')) # type: ignore
    elif status == 2:
        turtle.goto(0,0)
        turtle.write('YOU WIN',0,'center',('楷体',80,'normal')) # type: ignore



def draw_foods():
    if len(foods) == 0 : build_foods()
    for row,col, fc in foods:
        x = tx + col * s
        y = ty - row * s
        turtle.goto(x,y)
        c = colors['food'][fc]
        draw_rect(s,c,c)

def draw_snakes():
    for row,col in snakes:
        x = tx + col * s
        y = ty - row * s
        turtle.goto(x,y)
        c = colors['snake'][0]
        draw_rect(s,c,c)

def collision():
    global score
    srow,scol = snakes[-1]
    for frow,fcol, _ in foods:
        if srow == frow and scol == fcol:
            foods.remove((frow,fcol, _))
            score += 1
            return True
    return False 

def check(srow,scol):
    global status
    if srow < 0 or scol < 0 or srow >= row_num or scol >= col_num:
        status = 0
    elif (srow,scol) in snakes:
        status = 0
    elif score >= 50:
        status = 2

def moving():
    row,col = snakes[-1]
    new_row = row + drow
    new_col = col + dcol
    check(new_row, new_col)
    if status == 1:
        snakes.append((new_row,new_col))
        if not collision():
            snakes.pop(0)

def build_foods(x = 50):
    while x > 0:
        frow = random.randint(0,row_num - 1)
        fcol = random.randint(0,col_num-1)
        fcolor = random.randint(0,len(colors['food'])-1)
        flag = 1
        for row,col, _ in foods:
            if frow == row and fcol == col:
                flag = 0
                break

        if(frow,fcol) in snakes:
            flag = 0
        if flag == 1:
            foods.append((frow,fcol,fcolor))
            x -= 1

def move_up():
    global drow,dcol
    drow = -1
    dcol = 0
def move_down():
    global drow,dcol
    drow = 1
    dcol = 0
def move_left():
    global drow,dcol
    drow = 0
    dcol = -1
def move_right():
    global drow,dcol
    drow = 0
    dcol = 1
turtle.onkey(move_up,'Up')
turtle.onkey(move_up,'w')
turtle.onkey(move_down,'Down')
turtle.onkey(move_down,'s')
turtle.onkey(move_left,'Left')
turtle.onkey(move_left,'a')
turtle.onkey(move_right,'Right')
turtle.onkey(move_right,'d')
turtle.listen()

def run():
    turtle.clear()
    if status == 1:
        moving()
    draw_bg()
    draw_tips()
    draw_foods()
    draw_snakes()
    turtle.update()
    turtle.ontimer(run,200)

def main():
    init()
    run()
    turtle.done()

以上代码实则不完善!大家可以自己去拓展(不代表不能玩)

settings.py 文件代码(设置):

s = 40
col_num = 20
row_num = 10
w = col_num*s + 2*s
h = row_num*s + 2*s

tx = -col_num/2 * s
ty = row_num/2 * s

score = 0

status = 1

snakes = [(3,3),(3,4),(3,5),(2,5)]
drow = 0
dcol = -1

foods = [(2,2,0),(1,10,1)]

walls = [s]

colors = {
    'bg':('#F2F2F2','#D2D2D2'),
    'snake':('#3232F2','#5252D2'),
    'food':('#E2E232','#32F232'),
    'font':('#EE0000')
}

以上代码同样不完善,自己去拓展

tools.py(辅助函数):

import turtle

def draw_rect(edge,bgcolor,bdcolor='#000000'):
    turtle.color(bdcolor,bgcolor)
    turtle.begin_fill()
    turtle.down()
    for i in range(4):
        turtle.forward(edge)
        turtle.right(90)
    turtle.up()
    turtle.end_fill()

以上代码自己去拓展pygame库。

还有一个文件,有了这个文件才能运行起来。

main.py(运行):

import snake

if __name__ == '__main__':
    snake.main()

以上是这个游戏所用到的所有文件。注意:以上代码实则不完善,需要自己去拓展、丰富这些内容。

再放一次链接,想照着打的可以照着打(照着打要与视频里保持一致)

https://www.bilibili.com/video/BV1pa4y1D7tU/?spm_id_from=333.788

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值