Make a score system - python

How can I make a score system, that increases by one, when I hit square1. A score system, that restart back to 0, when I hit square2. And also loop back to the beginning position, when I hit square2. So loop back and restart the score to 0, when I hit square 2.
import turtle
import math
from time import sleep
wn = 0
player = turtle.Turtle()
square1 = turtle.Turtle()
square2 = turtle.Turtle()
speed = 1
def init():
wn = turtle.Screen()
wn.bgcolor("blue")
wn.tracer(3)
turtle.listen()
turtle.onkey(turnLeft, "Left")
turtle.onkey(turnRight, "Right")
def initCharacters():
player.color("red")
player.shape("circle")
player.penup()
player.speed(0)
player.setposition(25, 20)
square1.color("white")
square1.shape("square")
square1.penup()
square1.speed(0)
square1.setposition(100, 100)
square2.color("yellow")
square2.shape("square")
square2.penup()
square2.speed(0)
square2.setposition(150, 50)
def distanceIsLessThan(p, q, distance):
return math.pow(p.xcor() - q.xcor(), 2) + math.pow(p.ycor() - q.ycor(), 2) < math.pow(distance, 2)
def turnLeft():
player.left(90)
def turnRight():
player.right(90)
def main():
init()
initCharacters()
while True:
player.forward(speed)
if distanceIsLessThan(player, square1, 20) or \
distanceIsLessThan(player, square2, 20):
# print("Touch")
initCharacters()
sleep(0.02)
if __name__ == "__main__":
main()

This is basically what you want:
import turtle
import math
from time import sleep
#Adding the integer for the score
score=0
wn = 0
player = turtle.Turtle()
square1 = turtle.Turtle()
square2 = turtle.Turtle()
speed = 1
#Here Im making a new turtle for showing the score
turtle_score=turtle.Turtle()
turtle_score.penup()
turtle_score.hideturtle()
turtle_score.goto(-300.00,-245.00)
turtle_score.write("")
def init():
wn = turtle.Screen()
wn.bgcolor("blue")
wn.tracer(3)
turtle.listen()
turtle.onkey(turnLeft, "Left")
turtle.onkey(turnRight, "Right")
def initCharacters():
player.color("red")
player.shape("circle")
player.penup()
player.speed(0)
player.setposition(25, 20)
square1.color("white")
square1.shape("square")
square1.penup()
square1.speed(0)
square1.setposition(100, 100)
square2.color("yellow")
square2.shape("square")
square2.penup()
square2.speed(0)
square2.setposition(150, 50)
def distanceIsLessThan(p, q, distance):
return math.pow(p.xcor() - q.xcor(), 2) + math.pow(p.ycor() - q.ycor(), 2) < math.pow(distance, 2)
def turnLeft():
player.left(90)
def turnRight():
player.right(90)
def main():
init()
initCharacters()
global score
while True:
player.forward(speed)
#Checking which square the player collided with and updating the score.
if distanceIsLessThan(player, square1, 20):
score=score+1
player.fd(40)
turtle_score.undo()
turtle_score.write(str(score))
if distanceIsLessThan(player, square2, 20):
score=0
turtle_score.undo()
turtle_score.write(str(score))
# print("Touch")
initCharacters()
sleep(0.02)
if __name__ == "__main__":
main()
The score shows up at the bottom left corner of the screen.

Related

Score/points update in beginner python turtle game

I'm a newbie to python and I'm having a problem with the score in my turtle game. The score is updated the first time I collect the ball, but it does not update when I collect the ball on any subsequent occasion. I would like the score to increase by a number e.g. 2 every time a ball is collected.
Might someone be able to offer a solution?
I suspect the issue could lie in:
the scope of the variable 'score
the improper looping of any/some function
import turtle
import random
import math
screen = turtle.Screen()
screen.title("My game by python code")
screen.bgcolor("black")
screen.setup(width=600, height=600)
# Making the user 'bubble'
bubble = turtle.Turtle()
bubble.color("red")
bubble.shape("circle")
bubble.penup()
speed = 3
# Making the collection balls
collection_ball = turtle.Turtle()
collection_ball.color("red")
collection_ball.penup()
collection_ball.shape("circle")
collection_ball.shapesize(0.5, 0.5, 0.5)
ball_cor1 = random.randint(30, 280)
ball_cor2 = random.randint(30, 280)
collection_ball.setposition(ball_cor1, ball_cor2)
collection_ball.color("yellow")
# Scoring
points = turtle.Turtle()
points.color("yellow")
style = ('Courier', 30, 'italic')
points.penup()
points.goto(-200, 250)
points.write("Points: 0", font=style)
points.hideturtle()
# Turning
def turn_left():
bubble.left(90)
def turn_right():
bubble.right(90)
# Collection of the balls
def collection(a, b):
return abs(a.xcor() - b.xcor()) < 10 and abs(a.ycor() - b.ycor()) < 20
def collection_ball_restart():
collection_ball.color("black")
ball_cor1 = random.randint(30, 280)
ball_cor2 = random.randint(30, 280)
collection_ball.goto(ball_cor1, ball_cor2)
collection_ball.color("yellow")
bubble.forward(speed)
screen.ontimer(play_game, 10)
def play_game():
if collection(bubble, collection_ball):
score = 0
score += 2
points.clear()
points.write("Points: " + str(score), font=style)
collection_ball_restart()
bubble.forward(speed)
else:
bubble.forward(speed)
screen.ontimer(play_game, 10)
turtle.onkeypress(turn_left, "Left")
turtle.onkeypress(turn_right, "Right")
screen.listen()
play_game()
screen.mainloop()
In addition to the score initialization issue that #TimRoberts points out (+1), below is a rework of your code to simplify the logic:
from turtle import Screen, Turtle
from random import randint
FONT_STYLE = ('Courier', 30, 'italic')
screen = Screen()
screen.title("My game by python code")
screen.bgcolor('black')
screen.setup(width=600, height=600)
# Making the user 'bubble'
bubble = Turtle()
bubble.color('red')
bubble.shape('circle')
bubble.penup()
# Making the collection balls
collection_ball = Turtle()
collection_ball.color('yellow')
collection_ball.shape('circle')
collection_ball.shapesize(0.5)
collection_ball.penup()
ball_cor1 = randint(30, 280)
ball_cor2 = randint(30, 280)
collection_ball.setposition(ball_cor1, ball_cor2)
# Scoring
score = 0
speed = 3
points = Turtle()
points.hideturtle()
points.color('yellow')
points.penup()
points.goto(-200, 250)
points.write("Points: 0", font=FONT_STYLE)
# Turning
def turn_left():
bubble.left(90)
def turn_right():
bubble.right(90)
# Collection of the balls
def was_collected(bubble):
return bubble.distance(collection_ball) < 15
def collection_ball_reset():
collection_ball.hideturtle()
collection_ball.goto(randint(30, 280), randint(30, 280))
collection_ball.showturtle()
def play_game():
global score
if was_collected(bubble):
score += 2
points.clear()
points.write("Points: " + str(score), font=FONT_STYLE)
collection_ball_reset()
bubble.forward(speed)
screen.ontimer(play_game, 10)
screen.onkeypress(turn_left, 'Left')
screen.onkeypress(turn_right, 'Right')
screen.listen()
play_game()
screen.mainloop()
E.g. use hideturtle() and showturtle() instead of color tricks; minimize necessary calls to ontimer(); use built-in distance function.

Why aren't my turtles turning around with gooma.xcor()?

I'm remaking mario, and I have some goombas, but they aren't turning around at the end. I don't know why, since it looks fine to me. I know they don't have hitboxes, because I haven't added them yet, and I'm a beginer. Please use the same names.
import random
import math
import time
turt = turtle.Turtle()
tart = turtle.Turtle()
goomba = turtle.Turtle()
nb = turtle.Turtle()
qb = turtle.Turtle()
m = turtle.Turtle()
m.ht()
screen = turtle.Screen()
screen.tracer(0)
screen.bgcolor("lightblue")
turt.up()
turt.goto(-500,-350)
turt.down()
def block():
turt.color("goldenrod")
turt.begin_fill()
for i in range(4):
turt.forward(50)
turt.right(90)
turt.end_fill()
turt.ht()
b = -500
#r1
for i in range(20):
turt.st()
block()
turt.up()
b = b+50
turt.goto(b,-300)
turt.down()
tart.up()
tart.color("red")
tart.pensize("10")
tart.shape("circle")
tart.goto(-350,-290)
tart.down()
goomba.up()
goomba.color("brown")
goomba.shape("circle")
goomba.pensize(20)
goomba.goto(-200,-290)
goomba.down()
nb.up()
nb.goto(-100,-200)
nb.shape("square")
nb.pensize(10)
nb.color("brown")
nb.down()
nb2 = nb.clone()
nb2.goto(-80,-200)
qb.up()
qb.goto(-60,-200)
qb.color("yellow")
qb.shape("square")
qb.down()
nb3 = nb.clone()
nb3.goto(-40,-200)
goomba2 = goomba.clone()
goomba2.up()
goomba2.goto(200,-290)
def up():
tart.setheading(90)
screen.tracer(1)
for i in range(75):
tart.forward(1)
tart.setheading(270)
tart.forward(75)
screen.tracer(0)
def down():
tart.setheading(270)
tart.forward(10)
def right():
tart.setheading(0)
tart.forward(10)
def left():
tart.setheading(180)
tart.forward(10)
tart.up()
screen.onkey(up, "w")
screen.onkey(down, "s")
screen.onkey(right, "d")
screen.onkey(left, "a")
screen.listen()
goomba.up()
screen.update()
goomba.right(180)
goomba2.right(180)
tart.goto(-350,-280)
while True:
goomba.forward(1)
if tart.ycor() < -281:
tart.setheading(0)
tart.goto(-350,-280)
goomba2.forward(1)
if goomba.xcor() > 351:
goomba.right(180)
if goomba2.xcor() > 351:
goomba2.right(180)
screen.update()

Why do i get an error when the sprite hits the corner

from turtle import *
import turtle
import time
import random
this part down here is the moving for the sprite.
def up():
turtle.setheading(90)
turtle.forward(3)
def right():
turtle.setheading(0)
turtle.forward(3)
def left():
turtle.setheading(180)
turtle.forward(3)
def down():
turtle.setheading(270)
turtle.forward(3)
def pickup():
turtleXPos = int(turtle.pos()[0])
teki1XPos = int(teki1.pos()[0])
# if teki1YPos == turtleYPos and teki1XPos == turtleXPos:
turtleYPos = int(turtle.pos()[1])
teki1YPos = int(teki1.pos()[1])
if int(turtle.distance(teki1)) < 26:
teki1.color("purple")
font = ("Courier", 30, "normal")
teki1.write(coolcubecounter, font=font)
teki1.hideturtle()
teki1.goto(random.randint(0,100),random.randint(0,100))
teki1.showturtle()
turtle.listen()
turtle.clone()
#print(type((turtle.turtles().pop())))
#print(turtle.turtles())
#print(turtle.turtles().__getitem__(1))
wnd = turtle.Screen()
wnd.bgcolor("black")
#s=turtle.getscreen()
wnd.setup(666,666)
turtle.addshape("player.gif")
print(type(turtle))
teki=turtle.Turtle
#teki.circle(20)
turtle1=turtle.Turtle()
#turtle1=teki.clone(self= teki)
turtle.shape("player.gif")
#turtle.shape(circle())
penup()
turtle.getshapes()
#wteki.shape("player.gif")
turtle.onkeypress(up,"w")
turtle.onkeypress(right,"d")
turtle.onkeypress(left,"a")
turtle.onkeypress(down,"s")
turtle.onkey(pickup,"e")
teki1 =turtle.Turtle()
teki1.penup()
turtle.addshape("coolcube.gif")
teki1.shape("coolcube.gif")
teki1.goto(0,100)
cubeXandY=teki1.position()
playerXandY=turtle.position()
coolcubecounter=0
#print(cubeXandY==playerXandY)
#loop
#while True:
#for i in range(10):
#teki1.setpos(300, 0)
#pencolor("blue")
#up()
#right()
#for i in range(10):
#teki1.setpos(300, 300)
#pencolor("red")
#left()
#down()
exitonclick()
Your code is too messy for me to attempt to debug. Below is a rework of your code. See if this does what you want and clears up your bug(s):
from turtle import Screen, Turtle
from random import randint
FONT = ('Courier', 30, 'normal')
def up():
player.setheading(90)
player.forward(3)
def right():
player.setheading(0)
player.forward(3)
def left():
player.setheading(180)
player.forward(3)
def down():
player.setheading(270)
player.forward(3)
coolcubecounter = 0
def pickup():
global coolcubecounter
if player.distance(teki) < 26:
coolcubecounter += 1
teki.write(coolcubecounter, align='center', font=FONT)
teki.hideturtle()
teki.goto(randint(-300, 300), randint(-300, 300))
teki.showturtle()
screen = Screen()
screen.bgcolor('black')
screen.setup(666, 666)
# screen.addshape("player.gif")
# screen.addshape("coolcube.gif")
player = Turtle(shape='turtle')
# player.shape("player.gif")
player.color('red')
player.penup()
teki = Turtle(shape='turtle')
# teki.shape("coolcube.gif")
teki.color('purple')
teki.penup()
teki.sety(100)
screen.onkeypress(up, 'w')
screen.onkeypress(right, 'd')
screen.onkeypress(left, 'a')
screen.onkeypress(down, 's')
screen.onkey(pickup, 'e')
screen.listen()
screen.exitonclick()

Use of ontimer function to make two turtles move at same time

I 've been struggling to make both turtles move at the same time. Either one moves or they are both are frozen. I'm currently using the ontimer() function but still don't understand it completely.
The game is if you are wondering based of the paperio game but two players go against each other on the same keyboard and screen
My code:
from turtle import *
import turtle
p1f = True
p2f = True
title("1v1 Paperio")
p1move = Turtle()
p2move = Turtle()
t1 = Turtle()
t2 = Turtle()
screen = Screen()
def Setup1():
t1.pencolor("aquamarine")
t1.pensize(5)
t1.speed(10)
t1.fillcolor("light sea green")
t1.hideturtle()
t1.penup()
t1.goto(-200, -200)
t1.pendown()
t1.begin_fill()
for i in range(4):
t1.forward(50)
t1.left(90)
t1.end_fill()
p1move.penup()
p1move.goto(-175, -175)
p1move.pendown()
def Setup2():
t2.pencolor("crimson")
t2.pensize(5)
t2.speed(10)
t2.fillcolor("red")
t2.hideturtle()
t2.penup()
t2.goto(200, 200)
t2.pendown()
t2.begin_fill()
for i in range(4):
t2.forward(50)
t2.left(90)
t2.end_fill()
p2move.penup()
p2move.goto(225, 225)
p2move.pendown()
def p1setup():
p1move.pencolor("aquamarine")
p1move.pensize(5)
p1move.speed(10)
p1move.fillcolor("light sea green")
def p2setup():
p2move.pencolor("crimson")
p2move.pensize(5)
p2move.speed(10)
p2move.fillcolor("red")
# ycord
# heading
def p1moving():
def p1k1():
p1x1 = p1move.xcor()
p1y1 = p1move.ycor()
while p1f == True:
p1move.forward(1)
screen.ontimer(p1moving, 1)
def p1k2():
p1move.left(90)
def p1k3():
p1move.right(90)
def p2moving():
def p2k1():
p2f = True
p2x2 = p2move.xcor()
p2y2 = p2move.ycor()
while p2f == True:
p2move.forward(1)
screen.ontimer(p2moving, 1)
def p2k2():
p2move.left(90)
def p2k3():
p2move.right(90)
screen.listen()
screen.onkey(p1k1, "w")
screen.onkey(p1k2, "a")
screen.onkey(p1k3, "d")
screen.onkey(p2k1, "Up")
screen.onkey(p2k2, "Left")
screen.onkey(p2k3, "Right")
if __name__ == "__main__":
Setup1()
Setup2()
p1setup()
p2setup()
screen.mainloop()
Most of your code seems reasonable until you get to the key and timer event functions -- you have unused variables and functions that don't get called. Your functions defined inside functions are particularly problematic. I've reworked your code below to run as you describe. I've also done some speed optimizations to make it "play" a little better:
from turtle import Screen, Turtle
def setup1():
base1.hideturtle()
base1.color("light sea green", "aquamarine")
base1.pensize(5)
base1.penup()
base1.goto(-200, -200)
base1.pendown()
base1.begin_fill()
for _ in range(4):
base1.forward(50)
base1.left(90)
base1.end_fill()
pen1.color("light sea green", "aquamarine")
pen1.pensize(5)
pen1.setheading(0)
pen1.penup()
pen1.goto(-175, -175)
pen1.pendown()
def setup2():
base2.hideturtle()
base2.color("red", "pink")
base2.pensize(5)
base2.penup()
base2.goto(200, 200)
base2.pendown()
base2.begin_fill()
for _ in range(4):
base2.forward(50)
base2.left(90)
base2.end_fill()
pen2.color("red", "pink")
pen2.pensize(5)
pen2.setheading(180)
pen2.penup()
pen2.goto(225, 225)
pen2.pendown()
def p1k1():
screen.onkey(None, 'w')
def p1forward():
pen1.forward(1)
screen.update()
screen.ontimer(p1forward, 10)
p1forward()
def p1k2():
pen1.left(90)
screen.update()
def p1k3():
pen1.right(90)
screen.update()
def p2k1():
screen.onkey(None, 'Up')
def p2forward():
pen2.forward(1)
screen.update()
screen.ontimer(p2forward, 10)
p2forward()
def p2k2():
pen2.left(90)
screen.update()
def p2k3():
pen2.right(90)
screen.update()
screen = Screen()
screen.title("1v1 Paperio")
screen.tracer(False)
base1 = Turtle()
pen1 = Turtle()
setup1()
base2 = Turtle()
pen2 = Turtle()
setup2()
screen.onkey(p1k1, 'w')
screen.onkey(p1k2, 'a')
screen.onkey(p1k3, 'd')
screen.onkey(p2k1, 'Up')
screen.onkey(p2k2, 'Left')
screen.onkey(p2k3, 'Right')
screen.update()
screen.listen()
screen.mainloop()

Turtle window hanging

When I try to run my code, my python turtle window just hangs; I can't move also. I've tried removing the win_pen and it worked, but I don't know what inside the win_pen is making it hang.
It also gives me the spinning wheel since I am on Mac, and I am not sure if that is the problem for this. I'm on Big Sur 11.1 by the way.
edit: The indents are right on my screen, just a copy and paste problem
Code:
import turtle
import os
import math
import random
from random import randint
score = 0
# Set Up Screen
wn = turtle.Screen()
wn.bgcolor("black")
wn.title("test")
# Draw border
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.hideturtle()
border_pen.pensize(3)
for side in range(4):
border_pen.fd(600)
border_pen.lt(90)
# Draw Winning Area
win_pen = turtle.Turtle()
win_pen.hideturtle()
win_pen.shape("square")
win_pen.penup()
win_pen.setposition(0,267.7)
win_pen.shapesize(3,29.8)
# Show Score on Screen
score_pen = turtle.Turtle()
score_pen.speed(0)
score_pen.color("white")
score_pen.penup()
score_pen.setposition(-290, 303)
scorestring = "Score: %s" %score
score_pen.write(scorestring, False, align="left", font=("Ubuntu", 14, "normal"))
score_pen.hideturtle()
# Set up Player 1
player1 = turtle.Turtle()
player1.color("blue")
player1.shape("triangle")
player1.penup()
player1.speed(0)
player1.setposition(0, -250)
player1.setheading(90)
player1speed = 15
# Set Up Enemies
en = 8
enemies = []
for i in range(en):
enemies.append(turtle.Turtle())
for enemy in enemies:
enemy.color("red")
enemy.shape("square")
enemy.penup()
enemy.speed(0)
enemy.goto(randint(-280,280),randint(-280,280))
enemy.shapesize(2,2)
enemyspeed = 2
# Draw Winning Area
win_pen = turtle.Turtle()
win_pen.hideturtle()
win_pen.shape("square")
win_pen.penup()
win_pen.setposition(0,267.7)
win_pen.shapesize(3,29.8)
#Define bullet state
#ready - ready to fire
#fire - bullet is firing
bulletstate = "ready"
def left():
x = player1.xcor()
player1.setheading(180)
player1.forward(player1speed)
if x < -280:
x = - 280
player1.setx(x)
def right():
x = player1.xcor()
player1.setheading(0)
player1.forward(player1speed)
if x > 280:
x = 280
player1.setx(x)
def up():
y = player1.ycor()
player1.setheading(90)
player1.forward(player1speed)
if y > 280:
y = 280
player1.sety(y)
def down():
y = player1.ycor()
player1.setheading(270)
player1.forward(player1speed)
if y < -280:
y = 280
player1.sety(y)
def isCollision(t1, t2):
distance = math.sqrt(math.pow(t1.xcor()-t2.xcor(),2)+math.pow(t1.ycor()-t2.ycor(),2))
if distance < 15:
return True
else:
return False
turtle.listen()
turtle.onkey(left, "a")
turtle.onkey(right, "d")
turtle.onkey(up, "w")
turtle.onkey(down, "s")
# Main Game Loop
while True:
if isCollision(player1, win_pen):
player1.setposition(0, -250)
player1.setheading(90)
There are several problems with your code: don't use while True: in an event-driven world like turtle -- let the event handler do its job; your collision logic is incorrect as it measures from the center of the turtles whereas we're really only concerned with the y position of the two turtles; you seem to be resetting the player in the wrong direction; you implement the winning area twice.
I've rewritten, and simplified, your code below incorporating the above changes and some other tweaks:
from turtle import Screen, Turtle
from random import randint
ENEMY_COUNT = 8
PLAYER_SPEED = 15
def left():
player.setheading(180)
player.setx(max(-280, player.xcor() - PLAYER_SPEED))
check_collision(player, win_pen)
def right():
player.setheading(0)
player.setx(min(280, player.xcor() + PLAYER_SPEED))
check_collision(player, win_pen)
def up():
player.setheading(90)
player.sety(min(280, player.ycor() + PLAYER_SPEED))
check_collision(player, win_pen)
def down():
player.setheading(270)
player.sety(max(-280, player.ycor() - PLAYER_SPEED))
check_collision(player, win_pen)
def check_collision(player, win_pen):
if abs(player.ycor() - win_pen.ycor()) < 15:
player.sety(-250)
player.setheading(90)
score = 0
# Set Up Screen
screen = Screen()
screen.bgcolor('black')
# Draw border
border_pen = Turtle()
border_pen.hideturtle()
border_pen.pensize(3)
border_pen.color('white')
border_pen.speed('fastest')
border_pen.penup()
border_pen.setposition(-300, -300)
border_pen.pendown()
for _ in range(4):
border_pen.forward(600)
border_pen.left(90)
# Draw Winning Area
win_pen = Turtle()
win_pen.shape('square')
win_pen.shapesize(3, 29.8)
win_pen.color('gray')
win_pen.penup()
win_pen.sety(267.7)
# Show Score on Screen
score_pen = Turtle()
score_pen.hideturtle()
score_pen.color('white')
score_pen.penup()
score_pen.setposition(-290, 303)
scorestring = "Score: %s" %score
score_pen.write(scorestring, False, align='left', font=('Ubuntu', 14, 'normal'))
# Set up Player
player = Turtle()
player.shape('triangle')
player.color('blue')
player.speed('fastest')
player.setheading(90)
player.penup()
player.setx(-250)
# Set Up Enemies
enemies = []
for _ in range(ENEMY_COUNT):
enemy = Turtle()
enemy.color('red')
enemy.shape('square')
enemy.shapesize(2)
enemy.speed('fastest')
enemy.penup()
enemy.goto(randint(-280, 280), randint(-280, 280))
enemies.append(enemy)
screen.onkey(left, 'a')
screen.onkey(right, 'd')
screen.onkey(up, 'w')
screen.onkey(down, 's')
screen.listen()
screen.mainloop()

Categories