I am new in python game developing.I am using python 3.8.I write a code using python turtle module, but when in run it everything works fine but my left bar which is player 1 doesn't move down after pressing 's' key but moves upward on pressing 'w' key.It is not even giving a error.It is just a structure.Please help me!
import turtle
import time
import random
#variabals
delay=0.05
#screen
wn=turtle.Screen()
wn.bgcolor('black')
wn.title('pong')
wn.setup(height=700,width=600)
wn.tracer(0)
#left player
lbar=turtle.Turtle()
lbar.speed(0)
lbar.direction='stop'
lbar.color('white')
lbar.shape('square')
lbar.shapesize(6,1)
lbar.up()
lbar.goto(-270,100)
#right player
rbar=turtle.Turtle()
rbar.speed(0)
rbar.direction='stop'
rbar.color('white')
rbar.shape('square')
rbar.shapesize(6,1)
rbar.up()
rbar.goto(270,-270)
#pong ball
ball=turtle.Turtle()
ball.speed(0)
ball.shape('circle')
ball.color('red')
ball.shapesize(0.5)
ball.up()
ball.goto(0,0)
#functions
def move():
if rbar.direction=='up':
y=rbar.ycor()
rbar.sety(y+20)
if rbar.direction=='down':
y=rbar.ycor()
rbar.sety(y-20)
if lbar.direction=='up':
lbar.sety(lbar.ycor()+20)
if lbar.direction=='down':
y=lbar.ycor()
lbar.sety(y-20)
def rup():
rbar.direction='up'
def rdown():
rbar.direction='down'
def lup():
lbar.direction='up'
def ldown():
lbar.directon='down'
#inputs
wn.listen()
wn.onkey(lup,'w')
wn.onkey(ldown,'s')
wn.onkey(rup,'Up')
wn.onkey(rdown,'Down')
#gameloop
while True:
wn.update()
move()
time.sleep(delay)
wn.mainloop()
my left bar which is player 1 doesn't move down after pressing 's' key
My guess it's due to the typo in the following function:
def ldown():
lbar.directon='down'
lbar.directon -> lbar.direction
This should have shown up as an error message in your console.
My rework of your code to address the above, and several other issues:
from turtle import Screen, Turtle
# constants
DELAY = 50 # milliseconds
# functions
def move():
if rbar.direction == 'up':
rbar.sety(rbar.ycor() + 20)
elif rbar.direction == 'down':
rbar.sety(rbar.ycor() - 20)
if lbar.direction == 'up':
lbar.sety(lbar.ycor() + 20)
elif lbar.direction == 'down':
lbar.sety(lbar.ycor() - 20)
def rup():
rbar.direction = 'up'
def rdown():
rbar.direction = 'down'
def lup():
lbar.direction = 'up'
def ldown():
lbar.direction = 'down'
def gameloop():
screen.update()
move()
screen.ontimer(gameloop, DELAY)
# screen
screen = Screen()
screen.bgcolor('black')
screen.title('pong')
screen.setup(height=700, width=600)
screen.tracer(False)
# left player
lbar = Turtle()
lbar.color('white')
lbar.shape('square')
lbar.shapesize(6, 1)
lbar.penup()
lbar.goto(-270, 100)
lbar.direction = 'stop'
# right player
rbar = lbar.clone()
rbar.goto(270, -270)
rbar.direction = 'stop'
# pong ball
ball = Turtle()
ball.shape('circle')
ball.color('red')
ball.shapesize(0.5)
ball.penup()
# inputs
screen.onkey(lup, 'w')
screen.onkey(ldown, 's')
screen.onkey(rup, 'Up')
screen.onkey(rdown, 'Down')
screen.listen()
gameloop()
screen.mainloop()
Related
I am trying to make the game Pong.
I have everything (except moving the ball) set up but when I run it I can't move both paddles at the same time. Does anybody know what I need to do?
import time
import turtle
#window
Wn_width = 800
Wn_height = 600
Wn = turtle.Screen()
Wn.setup(Wn_width, Wn_height)
Wn.tracer(0)
Title = turtle.title("Pong")
Background_color = turtle.bgcolor("black")
#bats and ball
bat1 = turtle.Turtle("square")
bat1.color("white")
bat1.shapesize(3, 1)
bat1.penup()
bat1.setpos(360,0)
bat2 = turtle.Turtle("square")
bat2.color("white")
bat2.shapesize(3, 1)
bat2.penup()
bat2.setpos(-360, 0)
bal = turtle.Turtle("circle")
bal.color("white")
bal.penup()
#up down
def up():
bat1.sety(bat1.ycor() + 5)
if bat1.ycor() > 260:
bat1.sety(bat1.ycor() -5)
def down():
bat1.sety(bat1.ycor() - 5)
if bat1.ycor() < -250:
bat1.sety(bat1.ycor() + 5)
def up2():
bat2.sety(bat2.ycor() + 5)
if bat2.ycor() > 260:
bat2.sety(bat2.ycor() - 5)
def down2():
bat2.sety(bat2.ycor() - 5)
if bat2.ycor() < -250:
bat2.sety(bat2.ycor() + 5)
Wn.onkeypress(up, "Up")
Wn.onkeypress(down, "Down")
Wn.onkeyrelease(up, "Up")
Wn.onkeyrelease(down, "Down")
Wn.onkeypress(up2, "w")
Wn.onkeypress(down2, "s")
Wn.onkeyrelease(up2, "w")
Wn.onkeyrelease(down2, "s")
Wn.listen()
#main loop
while True:
Wn.update()
time.sleep(0.01)
Each paddle moves perfectly fine on its own, but when I try to move them simultaneously, for example while holding the "up" button, pressing the "w" button - the first paddle will just stop and the second will start moving. How can I be able to press both "up" (or "down") and "w" (or "s") at the same time and have both paddles move?
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()
I want to make a Space Invaders game but my enemies don't disappear if they get hit. Does anyone know how to fix it?
I already tried a for loop (as you will see) but it doesnt work:
import turtle as tr
wn = tr.Screen()
wn.tracer(0)
bullet = tr.Turtle()
player = tr.Turtle()
enimis = []
y = -250
def shoot():
player.direction = "up"
wn.onkey(shoot,"space")
while True:
if len(enimis) == 0:
for u in range(-210,210,60):
for o in range(100,260,60):
enimi = tr.Turtle()
enimi.setpos(u,o)
enimis.append(enimi)
if player.direction == "up":
bullet.penup()
x = player.xcor()
bullet.setpos(x,y)
bullet.pendown()
for p in range(550):
bullet.setpos(x,y+p)
for k in enimis:
if bullet.distance(k) < 25:
score += 10
if score > highscore:
highscored = True
else:
highscored = False
del k
hit = True
break
else:
hit = False
wn.update()
There aren't any error messages, the enemies just don't disappear.
I don't see why you're stuck on making dead enemies disappear when the code doesn't run at all due to this error:
if player.direction == "up":
AttributeError: 'Turtle' object has no attribute 'direction'
Nor could you hit an enemy since your player and enemies can't move and the player isn't pointing at an enemy to start with. Too much magical thinking and not enough code.
To answer your question, this can't work:
for k in enimis:
if bullet.distance(k) < 25:
# ...
del k
# ...
break
It either needs to be:
for k in enimis:
if bullet.distance(k) < 25:
# ...
enimis.remove(k) # remove by value
# ...
break
or:
for k in range(len(enimis)):
if bullet.distance(enimis[k]) < 25:
# ...
del enimis[k] # remove by index
# ...
break
Below is my complete rewrite of your code to get it to basically play: player can move left and right; bullets fire, hit enemies, score points, and enemies disappear; the score is shown on the screen; etc.
from turtle import Screen, Turtle
BASELINE = -250
FONT = ('Arial', 18, 'bold')
def left():
player.setx(player.xcor() - 5)
def right():
player.setx(player.xcor() + 5)
def shoot():
global firing
firing = True
firing = False
enemies = []
score = 0
bullet = Turtle('triangle')
bullet.hideturtle()
bullet.speed('fastest')
bullet.shapesize(0.5)
bullet.setheading(90)
bullet.penup()
player = Turtle('turtle')
player.hideturtle()
player.speed('fastest')
player.color('green')
player.setheading(90)
player.penup()
player.sety(BASELINE)
player.showturtle()
marker = Turtle()
marker.hideturtle()
marker.penup()
marker.goto(-300, 300)
marker.write("Score: {}".format(score), align='center', font=FONT)
def play():
global firing, score
if not enemies:
screen.tracer(False)
for x in range(-210, 210, 60):
for y in range(100, 260, 60):
enemy = Turtle('turtle')
enemy.color('red')
enemy.setheading(270)
enemy.penup()
enemy.setpos(x, y)
enemies.append(enemy)
screen.tracer(True)
if firing:
bullet.setx(player.xcor())
bullet.sety(BASELINE)
bullet.showturtle()
for p in range(0, 550, 5):
bullet.sety(BASELINE + p)
for enemy in enemies:
if bullet.distance(enemy) < 20:
score += 10
marker.undo()
marker.write("Score: {}".format(score), align='center', font=FONT)
enemy.clear()
enemy.hideturtle()
enemies.remove(enemy)
break
else: # no break
continue
break
bullet.clear()
bullet.hideturtle()
firing = False
screen.ontimer(play, 100)
screen = Screen()
screen.onkey(shoot, 'space')
screen.onkey(left, 'Left')
screen.onkey(right, 'Right')
screen.listen()
play()
screen.mainloop()
Still needed: moving enemies left, right and down; making bullet firing and player/enemy movement happen at the same time; add back highscore; etc.
I am trying to make a game where I can press space to shoot my bullet. There is a lot of lag. I am trying to figure out how to make the bullet disappear after it exits the screen. There is also a lot of lag. I am pretty sure the lag is from the bullet not resetting the screen after reaching the end. I imported time but I just can't seem to figure out how to use time.
This is what I tried:
# Importing GUI library
import turtle
import time
bullets = []
bullets2 = []
# Set speed, GUI, creates new turtle
t_speed = 5
bullet_speed = 50000
screen = turtle.Screen()
t = turtle.Turtle()
t2=turtle.Turtle()
screen.setup(700, 400)
# Arrow Keys as turtle movement
def forward():
t.forward(t_speed)
def left():
t.left(t_speed)
def right():
t.right(t_speed)
def back():
t.back(t_speed)
def forward2():
t2.forward(t_speed)
def left2():
t2.left(t_speed)
def right2():
t2.right(t_speed)
def back2():
t2.back(t_speed)
# Shoot a turtle from a turtle
def shoot():
# sets position of bullet at x and y of t
# spawn turtle at x and y
bullet = turtle.Turtle()
bullet.ht()
bullet.penup()
# Launch him
screen.addshape("uparrow.png")
bullet.shape("uparrow.png")
bullet.setheading(t.heading())
bullet.setposition(t.xcor(), t.ycor())
bullet.st()
bullet.forward(700)
bullet.speed(bullet_speed)
#TODO: Make less laggy by deleting bullet object after x seconds
def shoot2():
# set a timer
current = time.localtime().tm_sec
# sets position of bullet at x and y of t
# spawn turtle at x and y
bullet = turtle.Turtle()
bullets2.append(bullet)
bullet.ht()
bullet.penup()
# Launch him
screen.addshape("uparrow.png")
bullet.shape("uparrow.png")
bullet.setheading(t2.heading())
bullet.setposition(t2.xcor(), t2.ycor())
bullet.st()
bullet.forward(700)
bullet.speed(bullet_speed)
#TODO: Make less laggy by deleting bullet object after x seconds
#new = time.localtime().tm_sec
#if new > current + 3:
#bullets2.
def playGame():
# TODO: Health Bar
# TODO: Characters
t.penup()
t.setheading(5)
t2.penup()
# TODO
still_alive = True
# Movement
screen.onkey(back, "Down")
screen.onkey(left, "Left")
screen.onkey(right, "Right")
screen.onkey(shoot, "space")
screen.onkey(forward, "Up")
screen.onkey(back2, "S")
screen.onkey(left2, "A")
screen.onkey(right2, "D")
screen.onkey(shoot2, "Z")
screen.onkey(forward2, "W")
# Game Engine
screen.listen()
t.mainloop()
def gameStart():
# Title
print("Welcome to my game!")
# Menu; press Q to quit, Press p to play
startGame = True
while startGame == True:
inp = raw_input("Press p to play or Press q to quit")
if inp == "q":
exit()
elif inp == "p":
playGame()
startGame = False
else:
print("Incorrect prompt")
# Instructions
print("Use Arrow Keys to move. Press space to shoot")
def main():
gameStart()
if __name__ == "__main__":
main()
The object should disappear after some time.
Your progam appears to be a collection of misconceptions glued together with bad code management. Your bullet not only has lag, but it locks out all other action while it's in motion! Let's toss the time module idea and instead take advantage of turtle's own timer events to really let the bullets fly:
from turtle import Screen, Turtle
# Arrow Keys as turtle movement
def forward_1():
player_1.forward(player_speed)
def back_1():
player_1.back(player_speed)
def left_1():
player_1.left(player_speed)
def right_1():
player_1.right(player_speed)
def shoot_1():
screen.onkey(None, "space") # disable handler inside handler!
shoot(player_1)
screen.onkey(shoot_1, "space")
def forward_2():
player_2.forward(player_speed)
def left_2():
player_2.left(player_speed)
def right_2():
player_2.right(player_speed)
def back_2():
player_2.back(player_speed)
def shoot_2():
screen.onkey(None, "z")
shoot(player_2)
screen.onkey(shoot_2, "z")
def travel(bullet, milliseconds):
bullet.forward(bullet_speed)
if milliseconds:
screen.ontimer(lambda b=bullet, s=milliseconds - 100: travel(b, s), 100)
else:
bullet.hideturtle()
bullets.append(bullet)
# Shoot a bullet from a player
def shoot(player):
# sets position of bullet at x and y of player
# spawn turtle at x and y
if bullets:
bullet = bullets.pop(0)
else:
bullet = Turtle(visible=False)
# bullet.shape("uparrow.png")
bullet.shape('arrow')
bullet.speed('fastest')
bullet.penup()
# Launch him
bullet.color(player.fillcolor())
bullet.setheading(player.heading())
bullet.setposition(player.position())
bullet.showturtle()
travel(bullet, 2000)
bullets = []
# Set speed, GUI, creates new turtle
player_speed = 10
bullet_speed = 15
screen = Screen()
screen.setup(700, 400)
# screen.addshape("uparrow.png")
player_1 = Turtle('triangle')
player_1.speed('fastest')
player_1.color('red', 'pink')
player_1.penup()
player_1.setheading(90)
player_2 = Turtle('triangle')
player_2.speed('fastest')
player_2.color('blue', 'cyan')
player_2.penup()
player_2.setheading(270)
# Movement
screen.onkey(forward_1, "Up")
screen.onkey(back_1, "Down")
screen.onkey(left_1, "Left")
screen.onkey(right_1, "Right")
screen.onkey(shoot_1, "space")
screen.onkey(forward_2, "w")
screen.onkey(back_2, "s")
screen.onkey(left_2, "a")
screen.onkey(right_2, "d")
screen.onkey(shoot_2, "z")
# Game Engine
screen.listen()
screen.mainloop()
I have gotten an issue where an enemy turtle stops when I shoot. I am relatively new to python so I know that my code is pretty bad. I cant seem to spot why this happens but I'm assuming its got something to do with the while loop.
here is the code:
(i have added notes so it is easy to skip to important parts of it)
import turtle
import os
#wn is window
#bp = border
bullet = 'ready'
#screen setup
wn = turtle.Screen()
wn.bgcolor('black')
wn.title('SPACE.INVADERS')
#border
bp = turtle.Turtle()
bp.speed(0)
bp.color('green')
bp.penup()
bp.setposition(-300,-300)
bp.pendown()
count=0
while count != 5:
count= (count+1)
bp.fd(600)
bp.lt(90)
bp.hideturtle()
#player
p = turtle.Turtle()
p.color('red')
p.shape('triangle')
p.penup()
p.speed(0)
p.setposition(0,-250)
p.setheading(90)
#enemy
e = turtle.Turtle()
e.penup()
e.speed(0)
e.shape('square')
e.shapesize(1.25,1.25)
e.color('orange')
e.setpos(-250,250)
e.speed(1)
#p = player
#ps = player speed
ps = 15
#moving left and right
def left_mov():
x = p.xcor()
x -= ps
p.setx(x)
def right_mov():
x = p.xcor()
x += ps
p.setx(x)
#shooting
def shoot():
global bullet
if bullet == 'ready':
bullet = 'fire'
shot= turtle.Turtle()
shot.penup()
shot.speed(0)
shot.goto(p.pos())
shot.color('white')
shot.shape('triangle')
shot.shapesize(0.5)
shot.lt(90)
shot.speed(1)
shot.fd(550)
bullet = 'ready'
#bindings
turtle.listen()
turtle.onkey(left_mov, 'Left')
turtle.onkey(right_mov, 'Right')
turtle.onkey(shoot, 'space')
#enemy movement
while True:
e.fd(500)
e.rt(90)
e.fd(25)
e.rt(90)
e.fd(500)
e.lt(90)
e.fd(25)
e.lt(90)
I'm assuming its got something to do with the while loop
Yes, it shouldn't be there! In an event-driven world like turtle, there should never be a while True: loop. Instead, we need a timer event that fires off on regular intervals that does incremental updates of the objects in motion (enemy and bullet) so they appear to move at the same time. Below is my rework of your code using a timer event:
from turtle import Screen, Turtle
# moving left and right
def left_move():
player.setx(player.xcor() - player_speed)
def right_move():
player.setx(player.xcor() + player_speed)
# screen setup
screen = Screen()
screen.bgcolor('black')
screen.title('SPACE.INVADERS')
# border
border = Turtle(visible=False)
border.speed('fastest')
border.color('green')
border.penup()
border.setposition(-300, -300)
border.pendown()
for _ in range(4):
border.forward(600)
border.left(90)
# player
player = Turtle('triangle')
player.speed('fastest')
player.color('red')
player.penup()
player.setposition(0, -250)
player.setheading(90)
player_speed = 15
# enemy
enemy = Turtle('square')
enemy.speed('fast')
enemy.shapesize(1.25)
enemy.color('orange')
enemy.penup()
enemy.setpos(-250, 250)
enemy_speed = 6 # enemy speed
enemy_direction = 1 # enemy direction
# bullet
bullet = Turtle('triangle', visible=False)
bullet.speed('fastest')
bullet.color('white')
bullet.shapesize(0.5)
bullet.penup()
bullet.left(90)
bullet_speed = 9 # bullet speed
# shooting
def shoot():
if not bullet.isvisible():
bullet.goto(player.position())
bullet.showturtle()
def move():
global enemy_direction
if bullet.isvisible():
if bullet.ycor() > 275:
bullet.hideturtle()
else:
bullet.forward(bullet_speed)
# enemy movement
enemy.forward(enemy_direction * enemy_speed)
enemy.settiltangle(enemy.tiltangle() + 3) # just for fun
x, y = enemy.position()
if x > 250 or x < -250:
enemy_direction *= -1
enemy.sety(y - 25)
screen.ontimer(move, 50)
# bindings
screen.onkey(left_move, 'Left')
screen.onkey(right_move, 'Right')
screen.onkey(shoot, 'space')
screen.listen()
move()
screen.mainloop()
This should give you the basic functionality you need to move forward and add collision detection (bullet to enemy, enemy to player, player to wall) and scoring.
Also note that turtles are global entities so creating a new bullet every time you need one is a bad idea. Even if you evenually allow overlapping bullets, keep a reusable set of bullets for that purpose.