python turtle贪吃蛇

python turtle贪吃蛇


代码如下:

from turtle import *
import time
from winsound import PlaySound,SND_ASYNC
import random

tracer(10000000,0)
size=200
snakeSpeed=12
stepNum=20
stepSize=size/stepNum
points=0
direction=0
snakeLen=4
snake="0,0|-1,0|-2,0|-3,0|"
fruit=[1,1]
getFruit=False
sleepTime=1/snakeSpeed

setup(size+stepSize*10,size+stepSize*10)
screensize(size,size)

penup()
goto(size/2+stepSize/2,size/2+stepSize/2)
pendown()
goto(size/2+stepSize/2,-size/2-stepSize/2)
goto(-size/2-stepSize/2,-size/2-stepSize/2)
goto(-size/2-stepSize/2,size/2+stepSize/2)
goto(size/2+stepSize/2,size/2+stepSize/2)
penup()

def getSnake(barNum):
	barCount=0
	STR=""
	x=0;y=0
	for i in range(len(snake)):
		if barCount==barNum:
			j=i
			while snake[j]!=',':
				STR+=snake[j]
				j+=1
			x=int(STR)
			j+=1
			STR=""
			while snake[j]!='|':
				STR+=snake[j]
				j+=1
			y=int(STR)
			break
		if snake[i]=='|':
			barCount+=1
	return [x,y]

def move():
	#print("move!!!")
	#print(getFruit)
	newSnake=""
	if direction==0:
		readReturn=getSnake(0)
		newSnake+=str(readReturn[0]+1); newSnake+=","; newSnake+=str(readReturn[1]); newSnake+="|"
		for i in range(snakeLen-1):
			readReturn=getSnake(i)
			newSnake+=str(readReturn[0]); newSnake+=","; newSnake+=str(readReturn[1]); newSnake+="|"
	if direction==1:
		readReturn=getSnake(0)
		newSnake+=str(readReturn[0]); newSnake+=","; newSnake+=str(readReturn[1]-1); newSnake+="|"
		for i in range(snakeLen-1):
			readReturn=getSnake(i)
			newSnake+=str(readReturn[0]); newSnake+=","; newSnake+=str(readReturn[1]); newSnake+="|"
	if direction==2:
		readReturn=getSnake(0)
		newSnake+=str(readReturn[0]-1); newSnake+=","; newSnake+=str(readReturn[1]); newSnake+="|"
		for i in range(snakeLen-1):
			readReturn=getSnake(i)
			newSnake+=str(readReturn[0]); newSnake+=","; newSnake+=str(readReturn[1]); newSnake+="|"
	if direction==3:
		readReturn=getSnake(0)
		newSnake+=str(readReturn[0]); newSnake+=","; newSnake+=str(readReturn[1]+1); newSnake+="|"
		for i in range(snakeLen-1):
			readReturn=getSnake(i)
			newSnake+=str(readReturn[0]); newSnake+=","; newSnake+=str(readReturn[1]); newSnake+="|"
	if getFruit==True:
		readReturn=getSnake(snakeLen-2)
		newSnake+=str(readReturn[0]); newSnake+=","; newSnake+=str(readReturn[1]); newSnake+="|"
		#print("GET FRUIT !!!!!!!!!!!!!!!!!!!!!!!!")
	return newSnake

def drawSnake(clr):
	#print("drawSnake!!!")
	# if clr:
	# 	for i in range(snakeLen+2):
	# 		undo()
	#stepSize=size/stepNum
	pensize(stepSize-2)
	readReturn=getSnake(0)
	penup()
	goto(readReturn[0]*stepSize,readReturn[1]*stepSize,)
	pendown()
	for i in range(snakeLen):
		readReturn=getSnake(i)
		goto(readReturn[0]*stepSize,readReturn[1]*stepSize,)
	penup()

def check():
	#print("check!!!")
	readReturn=getSnake(0)
	global getFruit
	getFruit=False
	snkl=snakeLen
	for i in range(snakeLen-1):
		readReturn1=getSnake(i+1)
		if readReturn[0]==readReturn1[0] and readReturn[1]==readReturn1[1]:#hit self
			PlaySound("C:\\Windows\\media\\Windows Critical Stop.wav",SND_ASYNC)
			time.sleep(2)
			bye()
	if readReturn[0]>stepNum/2 or readReturn[1]>stepNum/2 or readReturn[0]<stepNum/-2 or readReturn[1]<stepNum/-2:#hit wall
		PlaySound("C:\\Windows\\media\\Windows Critical Stop.wav",SND_ASYNC)
		time.sleep(2)
		bye()
	if readReturn[0]==fruit[0] and readReturn[1]==fruit[1]:
		drawFruit()
		getFruit=True
		snkl=snakeLen+1
		PlaySound("C:\\Windows\\media\\Windows Hardware Insert.wav",SND_ASYNC)
	return snkl

def drawFruit():
	#print("drawFruit!")
	pensize(stepSize+5)
	goto((fruit[0])*stepSize,fruit[1]*stepSize)
	color("white")
	pendown()
	goto((fruit[0]+0.01)*stepSize,fruit[1]*stepSize)
	a=0
	while a!=snakeLen:
		fruit[0]=random.randint(stepNum/-2,stepNum/2)
		fruit[1]=random.randint(stepNum/-2,stepNum/2)
		a=0
		for i in range(snakeLen):
			readReturn=getSnake(i)
			if fruit[0]!=readReturn[0] or fruit[1]!=readReturn[1]:
				a+=1

	#outputStr='x'+str(fruit[0])+' y'+str(fruit[1])
	#print(outputStr)
	#stepSize=size/stepNum
	penup()
	goto((fruit[0])*stepSize,fruit[1]*stepSize)
	color("red")
	pendown()
	goto((fruit[0]+0.01)*stepSize,fruit[1]*stepSize)
	pensize(1)
	color("black")
	penup()
	goto(size/2+stepSize/2,size/2+stepSize/2)
	pendown()
	goto(size/2+stepSize/2,-size/2-stepSize/2)
	goto(-size/2-stepSize/2,-size/2-stepSize/2)
	goto(-size/2-stepSize/2,size/2+stepSize/2)
	goto(size/2+stepSize/2,size/2+stepSize/2)
	penup()

def key_D():
	global direction
	if direction!=2:
		direction=0
	#print("D!")
def key_S():
	global direction
	if direction!=3:
		direction=1
	#print("S!")
def key_A():
	global direction
	if direction!=0:
		direction=2
	#print("A!")
def key_W():
	global direction
	if direction!=1:
		direction=3
	#print("W!")

hideturtle()
penup()
pensize(size/stepNum-1)
drawFruit()
drawSnake(False)

onkeypress(key_W,"Up")
onkeypress(key_A,"Left")
onkeypress(key_S,"Down")
onkeypress(key_D,"Right")
onkeypress(key_W,"w")
onkeypress(key_A,"a")
onkeypress(key_S,"s")
onkeypress(key_D,"d")
listen()

while 1:
	time.sleep(sleepTime)
	color("white")
	drawSnake(True)
	snake=move()
	color("#235689")
	drawSnake(True)
	snakeLen=check()
	update()
	title(str(snakeLen-4))
	#print(getFruit)
	#print(snakeLen)

如果使用非windows系统请把用到winsound库的地方全删掉
这个是拿python3.7.14做的,python2.x无法运行,或者把那些onkeypress改成onkey也可以
第一次写,有很多调试的痕迹和没用的东西,请谅解
改了一下,这回自带windows音效。。。。。。
?

效果:
在这里插入图片描述

  • 10
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
以下是Python中使用turtle库实现贪吃蛇游戏的示例代码: ```python import turtle import random import time # 设置游戏窗口 win = turtle.Screen() win.title("贪吃蛇") win.bgcolor("black") win.setup(width=600, height=600) # 定义蛇头和食物 head = turtle.Turtle() head.shape("square") head.color("white") head.penup() head.goto(0, 0) head.direction = "stop" food = turtle.Turtle() food.shape("circle") food.color("red") food.penup() food.goto(random.randint(-290, 290), random.randint(-290, 290)) # 定义蛇的身体列表 body = [] # 定义蛇移动的函数 def move(): # 移动蛇的身体 for i in range(len(body) - 1, 0, -1): body[i].goto(body[i - 1].xcor(), body[i - 1].ycor()) # 移动蛇头 if head.direction == "up": head.sety(head.ycor() + 20) elif head.direction == "down": head.sety(head.ycor() - 20) elif head.direction == "left": head.setx(head.xcor() - 20) elif head.direction == "right": head.setx(head.xcor() + 20) # 检测蛇头是否与食物碰撞 if head.distance(food) < 20: # 食物移动到随机位置 food.goto(random.randint(-290, 290), random.randint(-290, 290)) # 添加一个新的身体方块 new_body = turtle.Turtle() new_body.shape("square") new_body.color("green") new_body.penup() body.append(new_body) # 检测蛇头是否与边界碰撞 if head.xcor() > 290 or head.xcor() < -290 or head.ycor() > 290 or head.ycor() < -290: time.sleep(1) head.goto(0, 0) head.direction = "stop" # 移除蛇的身体方块 for b in body: b.goto(1000, 1000) body.clear() # 检测蛇头是否与身体碰撞 for b in body: if head.distance(b) < 20: time.sleep(1) head.goto(0, 0) head.direction = "stop" # 移除蛇的身体方块 for b in body: b.goto(1000, 1000) body.clear() # 延迟移动蛇 time.sleep(0.1) # 循环调用移动函数 win.ontimer(move, 100) # 定义蛇头移动的函数 def go_up(): if head.direction != "down": head.direction = "up" def go_down(): if head.direction != "up": head.direction = "down" def go_left(): if head.direction != "right": head.direction = "left" def go_right(): if head.direction != "left": head.direction = "right" # 绑定键盘事件 win.listen() win.onkeypress(go_up, "Up") win.onkeypress(go_down, "Down") win.onkeypress(go_left, "Left") win.onkeypress(go_right, "Right") # 循环调用移动函数 move() # 主循环 win.mainloop() ``` 希望这个示例可以帮助你重新实现贪吃蛇游戏
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值