snake head is not moving - python

This snake game code is written in python-turtle. I want to move snake head, which is drawn using turtle module, but unfortunately it doesn't work. Also I add multiple foods for snake using for loop ,Might they have problem in collision, but i don't no how to rid this...?????
importing modules
import turtle
from turtle import *
import random
import time
delay = 0.1
level = 1
lives = 3
#score
score = 0
high_score = 0
#setting the screen
wn = turtle.Screen()
wn.title('Snake Game')
wn.bgcolor('black')
wn.bgpic('pic55.png')
#wn.addshape('snake head6.png')
wn.setup(width= 600, height= 600)
wn.tracer(0) #turns off the screen update
Snake head drawn using turtle
#snake head
head = turtle.Turtle()
def draw_circle(color, radius, x, y):
#head(turtle.Turtle())
head.penup()
head.fillcolor(color)
head.goto(x, y)
head.begin_fill()
head.circle(radius)
head.end_fill()
head.hideturtle()
draw_circle("#FF4500", 30, 0, -40) #face OrangeRed #FF4500 green #2CD717
draw_circle("#ffffff", 10, -10, -5) #left eye 9659BD purple
draw_circle("#ffffff", 10, 10, -5) #right eye B4BCE2 light blue
draw_circle("#4a70e3", 7, -8, -4) #5e7ede 9eb1eb 4a70e3 royalblue light colors
draw_circle("#4a70e3", 7, 8, -4)
draw_circle("#17202A", 5, -10, -5) ##17202A black
draw_circle("#17202A", 5, 10, -5)
#colors = random.choice(['green','black'])
#shapes = random.choice(['square'])
#head.shape(shapes)
#head.color(colors)
head.goto(0,0)
head.penup()
head.speed(0) #animation speed
head.direction = 'stop'
#segment = []
Multiple food
#max food
maxfoods =10
foods = []
#snake food
for count in range(maxfoods):
foods.append(turtle.Turtle())
foods[count].color('red')
foods[count].shape('square')
#food[count].shape(shapes)
#food[count].color(colors)
foods[count].penup()
foods[count].speed()
foods[count].speed(0)#animation speed
foods[count].setposition(random.randint(-300, 300) ,random.randint(-300, 300))
segment = []
#pen
pen = turtle.Turtle()
pen.speed(0)
pen.shape('square')
pen.color('white')
pen.penup()
pen.hideturtle()
pen.goto(0, 260)
pen.write("Score: 0 High Score: 0 Level: 1 Lives: 3",align = "center", font=("courier", 16, "normal"))
#functions
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'
def move():
if head.direction == 'up':
y = head.ycor()
head.sety(y + 20)
if head.direction == 'down':
y = head.ycor()
head.sety(y - 20)
if head.direction == 'left':
x = head.xcor()
head.setx(x - 20)
if head.direction == 'right':
x = head.xcor()
head.setx(x + 20)
#keyboard binding
wn.listen()
wn.onkeypress(go_up, 'Up')
wn.onkeypress(go_down, 'Down')
wn.onkeypress(go_left, 'Left')
wn.onkeypress(go_right, 'Right')
while loop
while True:
wn.update()
#check the border collision
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 segments in segment:
segment.goto(1000, 1000)
segment.clear()
#reset the score
score = 0
#reset the delay
delay = 0.1
#reset level
level = 1
pen.clear()
pen.write("Score: {} High Score: {} Level: {} Lives: {}".format(score, high_score, level, lives),align = "center", font=("courier", 16, "normal"))
#check for head collision with the food
for count in range(maxfoods):
#maxfood.forward(3)
if head.distance(foods) < 20:
#MOve the head random
x = random.randint(-290, 290)
y = random.randint(-290, 290)
foods.goto(x, y)
#add body to snake
new_segment = turtle.Turtle()
new_segment.speed(0)
new_segment.shape('square')
new_segment.color('green')
new_segment.penup()
segment.append(new_segment)
#shorten the delay
delay -= 0.001
#increase the score
score +=10
if score > high_score:
high_score = score
pen.clear()
pen.write("Score: {} High Score: {} Level: {} Lives: {}".format(score, high_score, level, lives),align = "center", font=("courier", 16, "normal"))
#Move the end body in reverse order
for index in range(len(segment)-1, 0, -1):
x = segment[index-1].xcor()
y = segment[index-1].ycor()
segment[index].goto(x, y)
#move the body 0 t where the head is
if len(segment) > 0:
x = head.xcor()
y = head.ycor()
segment[0].goto(x, y)
move()
#check for head collision with body/segment
for segments in segment:
if segments.distance(head) < 20:
time.sleep(1)
head.goto(0, 0)
head.direction = 'stop'
#hide the segment
for segments in segment:
segments.goto(1000, 1000)
#clear the segment list
segment.clear()
#reset the score
score = 0
#reset the level
level = 1
#update the score display
pen.clear()
pen.write("Score: {} High Score: {} Level: {} Lives: {}".format(score, high_score, level, lives),align = "center", font=("courier", 16, "normal"))
#levels
if level == 1 and score == 50:
level += 1
delay *= 0.9
if level == 2 and score == 100:
level += 1
delay *= 0.9
if level == 3 and score == 250:
level += 1
delay *= 0.9
if level == 4 and score == 350:
level += 1
delay *= 0.9
if level == 5 and score == 450:
level += 5
delay *= 0.9
time.sleep(delay)
wn.maingameloop()

Your code is a disaster. How did you write so much detailed code without testing whether the basics work? Examples of obvious problems:
if head.distance(foods) < 20:
The foods variable is a list, you should be testing:
if head.distance(foods[count]) < 20:
And this code:
#shorten the delay
delay -= 0.001
eventually drives delay negative and time.sleep() fails. And again here:
foods.goto(x, y)
The foods variable is a list, it doesn't respond to goto(). Also, you always draw your snake head in the same place, regardless of where the snake is located!
Below is a complete rework of a stripped down version of your program that attempts to get the basics working. The snake head moves; it can eat food to increase its score; border collisions are detected and reset the score and snake position:
from turtle import Screen, Turtle
from random import randint
FONT = ("courier", 16, "normal")
# score
score = 0
high_score = 0
# functions
def draw_circle(color, radius, x, y):
head.fillcolor(color)
head.goto(x, y)
head.begin_fill()
head.circle(radius)
head.end_fill()
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'
def move():
x, y = head.position()
if head.direction == 'up':
head.sety(y + 20)
elif head.direction == 'down':
head.sety(y - 20)
elif head.direction == 'left':
head.setx(x - 20)
elif head.direction == 'right':
head.setx(x + 20)
head.clear()
x, y = head.position()
draw_circle("#FF4500", 30, x + 0, y - 40) # face OrangeRed #FF4500 green #2CD717
draw_circle("#ffffff", 10, x - 10, y - 5) # left eye 9659BD purple
draw_circle("#ffffff", 10, x + 10, y - 5) # right eye B4BCE2 light blue
draw_circle("#4a70e3", 7, x - 8, y - 4) # royalblue
draw_circle("#4a70e3", 7, x + 8, y - 4)
draw_circle("#17202A", 5, x - 10, y - 5) # black
draw_circle("#17202A", 5, x + 10, y - 5)
head.setposition(x, y)
# setting the screen
screen = Screen()
screen.title('Snake Game')
screen.setup(width=600, height=600)
screen.bgcolor('black')
screen.tracer(False) # turns off screen update
# snake head
head = Turtle()
head.hideturtle()
head.penup()
head.direction = 'stop' # user defined property
move()
# max food
maxfoods = 10
foods = []
# snake food
for count in range(maxfoods):
food = Turtle()
food.color('red')
food.shape('square')
food.penup()
food.setposition(randint(-300, 300), randint(-300, 300))
foods.append(food)
# pen
pen = Turtle()
pen.hideturtle()
pen.shape('square')
pen.color('white')
pen.penup()
pen.sety(260)
pen.write("Score: 0 High Score: 0", align="center", font=FONT)
# keyboard binding
screen.onkeypress(go_up, 'Up')
screen.onkeypress(go_down, 'Down')
screen.onkeypress(go_left, 'Left')
screen.onkeypress(go_right, 'Right')
screen.listen()
def motion():
global score, high_score
# check the border collision
if head.xcor() > 290 or head.xcor() < -290 or head.ycor() > 290 or head.ycor() < -290:
head.goto(0, 0)
head.direction = 'stop'
# reset the score
score = 0
pen.clear()
pen.write("Score: {} High Score: {}".format(score, high_score), align="center", font=FONT)
# check for head collision with the food
for food in foods:
if head.distance(food) < 30:
# Move the food randomly
food.goto(randint(-290, 290), randint(-290, 290))
# increase the score
score += 10
if score > high_score:
high_score = score
pen.clear()
pen.write("Score: {} High Score: {}".format(score, high_score), align="center", font=FONT)
break
move()
screen.update()
screen.ontimer(motion, 100)
motion()
screen.mainloop()
Now you should be able to add back features, one at a time, and test them.

Related

I was using turtle for making snake game but facing problem while making functions of the program as it is not moving

#importing
import turtle
import random
import time
def snake_game():
#making head global so it can be used in other functions
global head
#scores
score = 0
high_score = 0
#setting up screen
wn = turtle.Screen()
wn.title("Snake Game")
wn.bgcolor('yellow')
wn.setup(width=600, height=600)
wn.tracer(0)
# making snake head
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("black")
head.penup()
head.goto(0,0)
head.direction = "stop"
#snake food
food= turtle.Turtle()
food.speed(0)
food.shape("square")
food.color("red")
food.penup()
food.goto(0,100)
segments = []
#scoreboards
sc = turtle.Turtle()
sc.speed(0)
sc.shape("square")
sc.color("black")
sc.penup()
sc.hideturtle()
sc.goto(0,260)
sc.write("score: 0 High score: 0", align = "center", font=("ds-digital", 24, "normal"))
#keyboard bindings
wn.listen()
wn.onkeypress(go_up, "w")
wn.onkeypress(go_down, "s")
wn.onkeypress(go_left, "a")
wn.onkeypress(go_right, "d")
#MainLoop
while True:
wn.update()
#check collision with border area
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"
#hide the segments of body
for segment in segments:
segment.goto(1000,1000) #out of range
#clear the segments
segments.clear()
#reset score
score = 0
#reset delay
delay = 0.1
sc.clear()
sc.write("score: {} High score: {}".format(score, high_score), align="center", font=("ds-digital", 24, "normal"))
#check collision
if head.distance(food) <20:
# move the food to random place
x = random.randint(-290,290)
y = random.randint(-290,290)
food.goto(x,y)
#add a new segment to the head
new_segment = turtle.Turtle()
new_segment.speed(0)
new_segment.shape("square")
new_segment.color("black")
new_segment.penup()
segments.append(new_segment)
#shorten the delay
delay -= 0.001
#increase the score
score += 10
if score > high_score:
high_score = score
sc.clear()
sc.write("score: {} High score: {}".format(score,high_score), align="center", font=("ds-digital", 24, "normal"))
#move the segments in reverse order
for index in range(len(segments)-1,0,-1):
x = segments[index-1].xcor()
y = segments[index-1].ycor()
segments[index].goto(x,y)
#move segment 0 to head
if len(segments)>0:
x = head.xcor()
y = head.ycor()
segments[0].goto(x,y)
move()
for segment in segments:
if segment.distance(head)<20:
time.sleep(1)
head.goto(0,0)
head.direction = "stop"
#hide segments
for segment in segments:
segment.goto(1000,1000)
segments.clear()
score = 0
delay = 0.1
#update the score
sc.clear()
sc.write("score: {} High score: {}".format(score,high_score), align="center", font=("ds-digital", 24, "normal"))
time.sleep(delay)
wun.mainloop()
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"
def move():
if head.direction == "up":
y = head.ycor()
head.sety(y+20)
if head.direction == "down":
y = head.ycor()
head.sety(y-20)
if head.direction == "left":
x = head.xcor()
head.setx(x-20)
if head.direction == "right":
x = head.xcor()
head.setx(x+20)
Well it was working fine as a normal program as long as the code in the function snake_game was the main program it was moving, but I have to append this game with other games. I have to call this game using a function, so when I converted it to a function it didn't move . The code is running and squares dots are also coming but on pressing keys the snake is not moving. I don't know where it went wrong.

Making python turtle based game reset on click

I'm trying to get my game to restart once the user clicks on the screen. I've tried wrapping the whole thing in a while loop, but that gave me errors about variables not being defined.
I've also tried wrapping the code in a function but that also gives me errors on variables.
Here's the code.
import turtle
import math
import random
import pygame
pygame.init()
pygame.mixer.init()
# MUSIC AND SOUND SETUP
pygame.mixer.music.load("Sounds/music.mp3")
pygame.mixer.music.play(loops=-1)
I'm using pygame just to add music into my game.
bubblefiredsound = pygame.mixer.Sound("Sounds/bubblefired.mp3")
enemyhitsound = pygame.mixer.Sound("Sounds/enemyhit.mp3")
# SCREEN SETUP
screen = turtle.Screen()
screen.bgcolor("black")
screen.title("Space Invaders")
screen.bgpic("TurtleInvadersBackground.png")
# CUSTOM SHAPES
turtle.register_shape("Enemy.gif")
turtle.register_shape("Turtle.gif")
turtle.register_shape("Bubble.gif")
# BORDERS
border_pen = turtle.Turtle()
border_pen.speed(0)
border_pen.color("white")
border_pen.penup()
border_pen.setposition(-300, -300)
border_pen.pendown()
border_pen.pensize(3)
for side in range(4):
border_pen.fd(600)
border_pen.lt(90)
border_pen.hideturtle()
# SCORE
score = 0
score_pen = turtle.Turtle()
score_pen.speed(0)
score_pen.color("white")
score_pen.penup()
score_pen.setposition(-290, 270)
scorestring = "Score: %s" % score
score_pen.write(scorestring, False, align="left", font=("Bubble3D", 20, "normal"))
score_pen.hideturtle()
# MAIN TURTLE
MajorTom = turtle.Turtle()
MajorTom.color("blue")
MajorTom.shape("Turtle.gif")
MajorTom.penup()
MajorTom.speed(0)
MajorTom.setposition(0, -250)
MajorTom.setheading(90)
playerspeed = 0
# NUMBER OF ENEMIES
number_of_enemies = 5
# PLACEHOLDER FOR ENEMIES
enemies = []
# ADD ENEMIES TO THE PLACEHOLDER
for i in range(number_of_enemies):
# CREATE ENEMIES
enemies.append(turtle.Turtle())
for enemy in enemies:
enemy.color("red")
enemy.shape("Enemy.gif")
enemy.penup()
enemy.speed(0)
x = random.randint(-200, 200)
y = random.randint(100, 250)
enemy.setposition(x, y)
enemyspeed = 5
# CREATE THE PROJECTILE BUBBLE
bubble = turtle.Turtle()
bubble.color("blue")
bubble.shape("Bubble.gif")
bubble.penup()
bubble.speed(0)
bubble.setheading(90)
bubble.hideturtle()
bubble.setpos(0, -300)
bubblespeed = 20
# BUBBLE STATE, READY = READY TO FIRE, FIRE = FIRING
bubblestate = "ready"
# MOVEMENT (LEFT AND RIGHT)
def move_left():
global playerspeed
playerspeed = -7
def move_right():
global playerspeed
playerspeed = 7
def stop_player():
global playerspeed
playerspeed = 0
def fire_bubble():
global bubblestate
if bubblestate == "ready":
bubblestate = "fire"
# MOVE BUBBLE TO MAJOR TOM
x = MajorTom.xcor()
y = MajorTom.ycor() + 10
bubble.setposition(x, y)
bubble.showturtle()
if bubblestate == "fire":
bubblefiredsound.play()
def CollisionDetection(t1, t2):
distance = math.sqrt(math.pow(t1.xcor() - t2.xcor(), 2) + math.pow(t1.ycor() - t2.ycor(), 2))
if distance < 32:
return True
else:
return False
# KEYBINDINGS
screen.listen()
screen.onkeypress(move_left, "a")
screen.onkeypress(move_right, "d")
screen.onkeyrelease(stop_player, "a")
screen.onkeyrelease(stop_player, "d")
screen.onkey(fire_bubble, "space")
This is the main loop, most of the code is put together here.
# GAME LOOP
while True:
# MOVE PLAYER
MajorTom.setx(MajorTom.xcor() + playerspeed)
# BORDER CONTROL
if MajorTom.xcor() > 285:
MajorTom.setx(285)
playerspeed = 0
elif MajorTom.xcor() < -285:
MajorTom.setx(-285)
playerspeed = 0
for enemy in enemies:
# ENEMY MOVEMENT
x = enemy.xcor()
x += enemyspeed
enemy.setx(x)
# MOVE THE ENEMY BACK AND DOWN
if enemy.xcor() > 280 or enemy.xcor() < -280:
# MOVE ALL ENEMIES DOWN
for e in enemies:
y = e.ycor()
y -= 40
e.sety(y)
# CHANGE ENEMY DIRECTION
enemyspeed *= -1
# BUBBLE HITS ENEMY
if CollisionDetection(bubble, enemy):
# PLAY BUBBLE BURST SOUND
enemyhitsound.play()
# RESET BUBBLE POSITION
bubble.hideturtle()
bubblestate = "ready"
bubble.setposition(0, -400)
# RESET ENEMY POSITION "SPAWN NEW ENEMY"
x = random.randint(-200, 200)
y = random.randint(100, 250)
enemy.setposition(x, y)
# ADD SCORE IF PLAYER HITS BUBBLE
score += 10
scorestring = "Score: %s" % score
score_pen.clear()
score_pen.write(scorestring, False, align="left", font=("Bubble3D", 20, "normal"))
if CollisionDetection(MajorTom, enemy) or enemy.ycor() < -300:
MajorTom.hideturtle()
enemy.hideturtle()
print("Game Over")
GameOverPen = turtle.Turtle()
GameOverPen.hideturtle()
GameOverPen.penup()
GameOverPen.goto(0,0)
GameOverPen.speed(0)
GameOverPen.color("pink")
GameOverPen.write("GAME OVER!", align="center", font=("Bubble3D", 90, "normal"))
GameOverPen.goto(0, -20)
GameOverPen.write("\nClick to try again!", align="center", font=("Arial", 20, "normal"))
break
# BUBBLE MOVEMENT
if bubblestate == "fire":
y = bubble.ycor()
y += bubblespeed
bubble.sety(y)
# CHECK TO SEE IF BUBBLE HAS HIT THE CEILING
if bubble.ycor() > 275:
bubble.hideturtle()
bubblestate = "ready"
you are looking for the turtle.onscreenclick function.
this function is called with the current x and y coordinates of the mouse when the screen is clicked.
def reset(x_pos, y_pos):
# reset the game
turtle.onscreenclick(reset)

How to open a window for a certain user discord.py

I'm coding a discord bot that you can play games with by typing a command such as !pong and it will open a window to play the classic pong game. The problem is, whenever any user other than me types the command(such as !snake), it opens the window for me, not for them. How can i make the window open for them?
Here is my code:
#client.command()
async def snake(ctx):
await ctx.send(f"Open snake game for {ctx.author.name}...")
# Score
score = 0
high_score = 0
# Set up the screen
wn = turtle.Screen()
wn.title("Snake Game")
wn.bgcolor("green")
wn.setup(width=600, height=600)
wn.tracer(0) # Turns off the screen updates
# Snake head
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("black")
head.penup()
head.goto(0,0)
head.direction = "stop"
# Snake food
food = turtle.Turtle()
food.speed(0)
food.shape("circle")
food.color("red")
food.penup()
food.goto(0,100)
segments = []
# Pen
pen = turtle.Turtle()
pen.speed(0)
pen.shape("square")
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 260)
pen.write("Score: 0 High Score: 0", align="center", font=("Courier", 24, "normal"))
# Functions
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"
def move():
if head.direction == "up":
y = head.ycor()
head.sety(y + 20)
if head.direction == "down":
y = head.ycor()
head.sety(y - 20)
if head.direction == "left":
x = head.xcor()
head.setx(x - 20)
if head.direction == "right":
x = head.xcor()
head.setx(x + 20)
# Keyboard bindings
wn.listen()
wn.onkeypress(go_up, "w")
wn.onkeypress(go_down, "s")
wn.onkeypress(go_left, "a")
wn.onkeypress(go_right, "d")
# Main game loop
while True:
wn.update()
# Check for a collision with the border
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"
# Hide the segments
for segment in segments:
segment.goto(1000, 1000)
# Clear the segments list
segments.clear()
# Reset the score
score = 0
# Reset the delay
delay = 0.1
pen.clear()
pen.write("Score: {} High Score: {}".format(score, high_score), align="center", font=("Courier", 24, "normal"))
# Check for a collision with the food
if head.distance(food) < 20:
# Move the food to a random spot
x = random.randint(-290, 290)
y = random.randint(-290, 290)
food.goto(x,y)
# Add a segment
new_segment = turtle.Turtle()
new_segment.speed(0)
new_segment.shape("square")
new_segment.color("grey")
new_segment.penup()
segments.append(new_segment)
# Shorten the delay
delay -= 0.001
# Increase the score
score += 10
if score > high_score:
high_score = score
pen.clear()
pen.write("Score: {} High Score: {}".format(score, high_score), align="center", font=("Courier", 24, "normal"))
# Move the end segments first in reverse order
for index in range(len(segments)-1, 0, -1):
x = segments[index-1].xcor()
y = segments[index-1].ycor()
segments[index].goto(x, y)
# Move segment 0 to where the head is
if len(segments) > 0:
x = head.xcor()
y = head.ycor()
segments[0].goto(x,y)
move()
# Check for head collision with the body segments
for segment in segments:
if segment.distance(head) < 20:
time.sleep(1)
head.goto(0,0)
head.direction = "stop"
# Hide the segments
for segment in segments:
segment.goto(1000, 1000)
# Clear the segments list
segments.clear()
# Reset the score
score = 0
# Reset the delay
delay = 0.1
# Update the score display
pen.clear()
pen.write("Score: {} High Score: {}".format(score, high_score), align="center", font=("Courier", 24, "normal"))
time.sleep(delay)
wn.mainloop()`
Can anyone help me?
You cannot have it open for them. You can only have it open for the person hosting the bot, if you would like this to work you would need them to download the bot themselves and run it. You could learn to make a browser-based game(will require knowledge of HTML/CSS/js) and generate a new link so they can play on their own browser.
The problem is that you are waiting for key presses here:
wn.listen()
wn.onkeypress(go_up, "w")
wn.onkeypress(go_down, "s")
wn.onkeypress(go_left, "a")
wn.onkeypress(go_right, "d")
While you should be waiting for messages using bot.wait_for(). You can read the official documentation for more information.

Get snake (list of turtles) to restart after self collision?

How would I get my turtle to restart in the middle of screen once it collides with it's own body?
from turtle import Screen, Turtle
import random
import time
DELAY = 100
def move():
if direction == 'up':
y = turtle.ycor()
turtle.sety(y + 20)
elif direction == 'down':
y = turtle.ycor()
turtle.sety(y - 20)
elif direction == 'left':
x = turtle.xcor()
turtle.setx(x - 20)
elif direction == 'right':
x = turtle.xcor()
turtle.setx(x + 20)
screen.update()
screen.ontimer(move, DELAY)
if turtle.xcor()>490 or turtle.xcor()<-490 or turtle.ycor()>490 or turtle.ycor()<-490:
time.sleep(1)
turtle.goto(0,0)
turtle.direction = "stop"
for section in sections
section.goto(1000, 1000)
sections.clear()
if turtle.distance(food) < 20:
x = random.randint(-390, 390)
y = random.randint(-390, 390)
food.goto(x, y)
new_section = Turtle()
new_section.speed(0)
new_section.shape("square")
new_section.color("orange", "grey")
new_section.penup()
sections.append(new_section)
for index in range(len(sections)-1,0, -1):
x = sections[index-1].xcor()
y = sections[index-1].ycor()
sections[index].goto(x, y)
if len(sections) > 0:
x = turtle.xcor()
y = turtle.ycor()
sections[0].goto(x, y)
def up():
global direction
direction = 'up'
def down():
global direction
direction = 'down'
def left():
global direction
direction = 'left'
def right():
global direction
direction = 'right'
screen = Screen()
screen.title(" Snakebite mini Game")
screen.bgcolor('brown')
screen.setup(width=800, height=700)
screen.tracer(0)
turtle = Turtle()
turtle.shape('turtle')
turtle.speed(0)
turtle.penup()
food = Turtle()
food.shape('circle')
food.color("red", "yellow")
food.speed(0)
food.penup()
food.goto(0,100)
sections = []
direction = 'stop'
screen.onkey(up, 'Up')
screen.onkey(down, 'Down')
screen.onkey(left, 'Left')
screen.onkey(right, 'Right')
screen.listen()
# main game loop
move()
screen.mainloop()
The basic answer is something like:
if any(turtle.distance(section) < 20 for section in sections):
turtle.goto(0, 0)
direction = 'stop'
...
But be warned, this means that doing a 180 is now a fatal move!
Complete code rework with optimizations, style tweaks and changes to make it more playable:
from turtle import Screen, Turtle
from random import randint
DELAY = 100
def up():
global direction
direction = 'up'
turtle.setheading(90)
def down():
global direction
direction = 'down'
turtle.setheading(270)
def left():
global direction
direction = 'left'
turtle.setheading(180)
def right():
global direction
direction = 'right'
turtle.setheading(0)
def move():
global direction
x, y = old_position = turtle.position()
if direction == 'up':
turtle.sety(y + 20)
elif direction == 'down':
turtle.sety(y - 20)
elif direction == 'left':
turtle.setx(x - 20)
elif direction == 'right':
turtle.setx(x + 20)
if direction != 'stop':
if sections:
if any(turtle.distance(section) < 20 for section in sections):
turtle.goto(0, 0)
direction = 'stop'
for section in sections:
section.hideturtle()
sections.clear()
else:
last_position = sections[-1].position()
if len(sections) > 1:
for index in range(len(sections) - 1, 0, -1):
sections[index].goto(sections[index - 1].position())
sections[0].goto(old_position)
old_position = last_position
if not (-390 < turtle.xcor() < 390 and -390 < turtle.ycor() < 390):
turtle.goto(0, 0)
direction = 'stop'
for section in sections:
section.hideturtle()
sections.clear()
if turtle.distance(food) < 20:
food.goto(randint(-380, 380), randint(-380, 380))
new_section = Turtle()
new_section.shape('square')
new_section.speed('fastest')
new_section.color('orange', 'grey')
new_section.penup()
new_section.goto(old_position)
sections.append(new_section)
screen.update()
screen.ontimer(move, DELAY)
screen = Screen()
screen.title("Snakebite mini Game")
screen.bgcolor('brown')
screen.setup(width=800, height=800)
screen.tracer(False)
turtle = Turtle()
turtle.shape('triangle')
turtle.speed('fastest')
turtle.color('orange', 'grey')
turtle.penup()
food = Turtle()
food.shape('circle')
food.speed('fastest')
food.color('red', 'yellow')
food.penup()
food.goto(randint(-380, 380), randint(-380, 380))
sections = []
direction = 'stop'
screen.onkey(up, 'Up')
screen.onkey(down, 'Down')
screen.onkey(left, 'Left')
screen.onkey(right, 'Right')
screen.listen()
# main game loop
move()
screen.mainloop()

python - penalty game how to speed up element

I've created simple penalty game and all works fine but I want to improve it a bit. Goal moves on sides itself and want I want to do is speeding it up when scored. I understand when dx is negative it must be += 1 and if dx is positive it must be opposite so += -1. I thought about for loop for dx in range(-270, 0, -270) and the second one for prositive variables. I'm beginner in python and programming itself, so I appreciate any advice. I want to speed up SL, SP and P. Those objects create the goal.
import turtle
import time
sd = 0.1
wn = turtle.Screen()
wn.bgcolor("black")
wn.title("karne")
wn.setup(width=800, height=600)
wn.tracer(0)
#pilka
ball = turtle.Turtle()
ball.shape("circle")
ball.color("green")
ball.speed(0)
ball.penup()
ball.goto(0, -275)
ball.direction = "stop"
score = 0
miss = 0
#scoring
pen = turtle.Turtle()
pen.speed(0)
pen.shape("square")
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 0)
#slupek lewy
sl = turtle.Turtle()
sl.shape("square")
sl.color("white")
sl.shapesize(stretch_wid=3, stretch_len=1)
sl.speed(0)
sl.penup()
sl.goto(-80, 270)
sl.dx = sd
#slupek prawy
sp = turtle.Turtle()
sp.shape("square")
sp.color("white")
sp.shapesize(stretch_wid=3, stretch_len=1)
sp.speed(0)
sp.penup()
sp.goto(80, 270)
sp.dx = sd
#poprzeczka
p = turtle.Turtle()
p.shape("square")
p.color("white")
p.shapesize(stretch_wid=7, stretch_len=1)
p.speed(0)
p.seth(90)
p.penup()
p.goto(0, 290)
p.dx = sd
score = 0
miss = 0
#function
def right():
x = ball.xcor()
x +=20
ball.setx(x)
def left():
x = ball.xcor()
x -=20
ball.setx(x)
def shoot():
ball.direction = "up"
def shoot2():
ball.direction = "stop"
def shoot1():
if ball.direction == "up":
y = ball.ycor()
ball.sety(y+0.5)
#binds
wn.listen()
wn.onkeypress(right, "d")
wn.onkeypress(left, "a")
wn.onkeypress(shoot, "space")
while True:
#goal moving
sl.setx(sl.xcor() + sl.dx)
sp.setx(sp.xcor() + sp.dx)
p.setx(p.xcor() + p.dx)
#goal borders check
if sl.xcor() > 250:
sl.setx(250)
sl.dx *= -1
if sl.xcor() < -390:
sl.setx(-390)
sl.dx *= -1
if sp.xcor() > 390:
sp.setx(390)
sp.dx *= -1
if sp.xcor() < -250:
sp.setx(-250)
sp.dx *= -1
if p.xcor() > 320:
p.setx(320)
p.dx *= -1
if p.xcor() < -320:
p.setx(-320)
p.dx *= -1
#ball and goal check
if (ball.ycor() > 270 and ball.ycor() < 280) and (ball.xcor() < p.xcor() + 50 and ball.xcor() > p.xcor() -40):
score += 1
pen.clear()
pen.write("Score:{} Miss:{} ".format(score, miss), align="center", font=("Courier", 24, "normal"))
shoot2()
ball.goto(0, -275)
if ball.ycor() > 295:
miss += 1
ball.goto(0, -275)
score = 0
pen.clear()
pen.write("Score:{} Miss:{} ".format(score, miss), align="center", font=("Courier", 24, "normal"))
shoot2()
shoot1()
wn.update()
With a program like this, the fewer objects you try to move in real time, the better. Your goal is three pieces that have to be be moved in unison. The primary fix below is to define the goal as a turtle shape so the goal is only one piece that needs to be manipulated. The secondary fix below is to replace while True:, which has no place in an event-driven world, with a timed event:
from turtle import Screen, Turtle
sd = 1.0
FONT = ("Courier", 24, "normal")
def right():
ball.forward(20)
def left():
ball.backward(20)
def shoot():
ball.direction = "up"
def shoot2():
ball.direction = "stop"
def shoot1():
if ball.direction == "up":
ball.sety(ball.ycor() + sd * 2)
wn = Screen()
wn.bgcolor("black")
wn.title("karne")
wn.setup(width=800, height=600)
wn.tracer(False)
wn.register_shape("goal", ((-90, 30), (90, 30), (90, -30), (70, -30), (70, 10), (-70, 10), (-70, -30), (-90, -30)))
# pilka
ball = Turtle("circle")
ball.color("green")
ball.speed('fastest')
ball.penup()
ball.sety(-275)
ball.direction = "stop"
# scoring
pen = Turtle(visible=False)
pen.speed('fastest')
pen.color("white")
pen.penup()
# poprzeczka
p = Turtle("goal")
p.color("white")
p.speed('fastest')
p.seth(90)
p.penup()
p.sety(270)
p.dx = sd
score = 0
miss = 0
# binds
wn.onkeypress(right, "d")
wn.onkeypress(left, "a")
wn.onkeypress(shoot, "space")
wn.listen()
def move():
global score, miss
# goal moving
p.setx(p.xcor() + p.dx)
# goal borders check
if p.xcor() > 330:
p.setx(330)
p.dx *= -1
elif p.xcor() < -330:
p.setx(-330)
p.dx *= -1
# ball and goal check
if 270 < ball.ycor() < 280 and ball.distance(p) < 50:
score += 1
pen.clear()
pen.write("Score:{} Miss:{} ".format(score, miss), align="center", font=FONT)
shoot2()
ball.goto(0, -275)
elif ball.ycor() > 295:
miss += 1
score = 0
pen.clear()
pen.write("Score:{} Miss:{} ".format(score, miss), align="center", font=FONT)
shoot2()
ball.goto(0, -275)
shoot1()
wn.update()
wn.ontimer(move, 25)
move()
wn.tracer(True)
wn.mainloop()
Plus lots of other little fixes to streamline the code.

Categories

Resources