make bouncing turtle with python - python

I am a beginner with python and I wrote this code to make bouncing ball with python turtle it works but have some errors like the ball disappearing
import turtle
turtle.shape("circle")
xdir = 1
x = 1
y = 1
ydir = 1
while True:
x = x + 3 * xdir
y = y + 3 * ydir
turtle.goto(x , y)
if x >= turtle.window_width():
xdir = -1
if x <= -turtle.window_width():
xdir = 1
if y >= turtle.window_height():
ydir = -1
if y <= -turtle.window_height():
ydir = 1
turtle.penup()
turtle.mainloop()

Although your approach to the problem works (my rework):
import turtle
turtle.shape("circle")
turtle.penup()
x, y = 0, 0
xdir, ydir = 3, 3
xlimit, ylimit = turtle.window_width() / 2, turtle.window_height() / 2
while True:
x = x + xdir
y = y + ydir
if not -xlimit < x < xlimit:
xdir = -xdir
if not -ylimit < y < ylimit:
ydir = -ydir
turtle.goto(x, y)
turtle.mainloop()
In the long run, it's the wrong approach to take. In this case, due to the infinite loop while True, the mainloop() method is never called so no other turtle event handlers are active. For example, if we wanted to use exitonclick() instead of mainloop(), it wouldn't work. Instead consider:
import turtle
turtle.shape("circle")
turtle.penup()
x, y = 0, 0
xdir, ydir = 3, 3
xlimit, ylimit = turtle.window_width() / 2, turtle.window_height() / 2
def move():
global x, y, xdir, ydir
x = x + xdir
y = y + ydir
if not -xlimit < x < xlimit:
xdir = -xdir
if not -ylimit < y < ylimit:
ydir = -ydir
turtle.goto(x, y)
turtle.ontimer(move, 5)
turtle.ontimer(move, 5)
turtle.exitonclick()
Here we've turned control back over to the mainloop and the motion is on an event timer. Other turtle events can execute so exitonclick() works. Just something to think about going forward before you program yourself, and your turtle, into a corner.

You need window_width()/2 and window_height()/2 to keep inside window.
ie.
if x >= turtle.window_width()/2:
xdir = -1
if x <= -turtle.window_width()/2:
xdir = 1
if y >= turtle.window_height()/2:
ydir = -1
if y <= -turtle.window_height()/2:
ydir = 1

You should put
turtle.penup()
Before the while loop to make your code better and a little bit faster. It is almost a bug!

You can bounce your wall, if you want to bounce it from upper wall, the screen width is 800 and length is 600
from turtle import turtle
turtle=Turtle()
def move(self)://This will move your ball in diagonal direction
x_dir=self.xcor()+self.x
y_dir=self.ycor()+self.y
self.goto(x_dir,y_dir)
def bounce(self)://This will bounce back
self.y *=-1
turtle.bounce()
This code is running because I did it with inheritance. You need to create a class then inherit all the properties and then create two methods there and then call those functions in the main class.

Related

Trying to fix a problem with finding neighbors in Conway's Game of Life

I was trying to recreate Conway's Game of Life in python using Tkinter, but I got stuck while checking for the neighbors. I can't seem to find the solution to my problem.
If a cell is alive it is stored using numpy, 0 for the dead cells and 1 for the living cells. The function "get_neighbours" checks if the cell is not in a corner or next to a side and it returns the ammount of neighbours each cell has. The function "recalculate" basically makes a new board with 0s and 1s which then replaces the original board and redraws everything. But when compared to an already existing game the progress is different.
import tkinter as tk
import numpy as np
win = tk.Tk()
WIDTH = 500
HEIGHT = 500
vs = 10
absvs = vs
cells = np.zeros((WIDTH//vs, HEIGHT//vs), dtype=int)
cells_new = np.zeros((WIDTH//vs, HEIGHT//vs), dtype=int)
def get_neighbours(x, y):
total = 0
if x > 0:
total += cells[x - 1, y]
if x > 0 and y > 0:
total += cells[x - 1, y - 1]
if y > 0:
total += cells[x, y - 1]
if x > 0 and y < (HEIGHT // absvs - 1):
total += cells[x - 1, y + 1]
if x < (WIDTH // absvs - 1):
total += cells[x + 1, y]
if x < (WIDTH // absvs - 1) and y < (HEIGHT // absvs - 1):
total += cells[x + 1, y + 1]
if y < (HEIGHT // absvs - 1):
total += cells[x, y + 1]
if x > 0 and y < (HEIGHT // absvs - 1):
total += cells[x - 1, y + 1]
return total
def recalculate():
global cells, cells_new
for y in range(HEIGHT//absvs):
for x in range(WIDTH//absvs):
temp = get_neighbours(x, y)
if (temp == 2 and cells[x, y] == 1) or (temp == 3 and cells[x, y] == 1):
cells_new[x, y] = 1
elif temp == 3 and cells[x, y] == 0:
cells_new[x, y] = 1
elif temp < 2 or temp > 3:
cells_new[x, y] = 0
cells = cells_new
canvas.delete("all")
create_stage()
redraw_cell()
def slider_changer(e):
global vs
canvas.delete("all")
vs = w.get()
create_stage()
redraw_cell()
def create_cell(e):
global cells
tx = e.x // vs
ty = e.y // vs
x = tx * vs
y = ty * vs
canvas.create_rectangle(x, y, x + vs, y + vs, fill="gray")
cells[tx, ty] = 1
print(get_neighbours(tx, ty))
def redraw_cell():
for x in range(WIDTH//vs):
for y in range(HEIGHT//vs):
if cells[x, y] == 1:
canvas.create_rectangle(x * vs, y * vs, x * vs + vs, y * vs + vs, fill="gray")
def create_stage():
for x in range(WIDTH//vs):
canvas.create_line(x*vs, 0, x*vs, HEIGHT)
for y in range(HEIGHT//vs):
canvas.create_line(0, y*vs, WIDTH, y*vs)
canvas = tk.Canvas(width = WIDTH, height = HEIGHT, bg = "white")
canvas.pack()
w = tk.Scale(win, from_=10, to=50, orient="horizontal", command = slider_changer, length = 500)
w.pack()
w2 = tk.Button(win, text = "PRESS ME!!!", command = recalculate)
w2.pack()
create_stage()
canvas.bind("<Button-1>", create_cell)
win.mainloop()
There are these issues in your code:
In get_neighbours the last if block is the same as the fourth if block, and so there is a neighbor that is counted twice and another neighbor that isn't counted at all (the one at x + 1 and y - 1). So replace this:
if x > 0 and y < (HEIGHT // absvs - 1):
total += cells[x - 1, y + 1]
with:
if x < (WIDTH // absvs - 1) and y > 0:
total += cells[x + 1, y - 1]
In recalculate the assignment to cells at the end is making you lose one of the two arrays. Now both cells and new_cells reference the very same array1. This means the next iteration will not be calculated correctly. Instead, you should copy the content of cells_new into cells. So replace:
cells = cells_new
with:
cells = cells_new.copy()
In recalculate the if...elif..elif construct (inside the double loop) does not deal with the case where temp == 2 and cells[x, y] == 1 and so cells_new[x, y] might not be reset to 0 when it should. In fact, the last part of this construct should not have a condition; it should be a catch-all for all states that the previous checks did not deal with. So replace:
elif temp < 2 or temp > 3:
cells_new[x, y] = 0
with:
else:
cells_new[x, y] = 0
1 It is not helping that several websites, including https://www.geeksforgeeks.org/how-to-copy-numpy-array-into-another-array/ and https://www.askpython.com/python-modules/numpy/numpy-copy, wrongly assert that an assignment of one numpy array to another makes a copy. That is not true.

Python click every point inside a 200px x 200px square

I want to make a python script that clicks every point inside a 200px x 200px square. I'm using a library that's called pyautogui and I tried to do it, but it didn't work as fine as I would like. Mouse only clicks in the middle of the screen. How can I fix that?
Here is a photo of the square and then there is the code that I actually have.
200px x 200px square
Code:
import pyautogui
import time
time.sleep(5)
exit_key = KeyCode(char='e')
pyautogui.FAILSAFE = False
x=700
y=400
for i in range(500):
if x <= 900 and y <= 400:
x= x + 1
pyautogui.click(x,y)
time.sleep(0.001)
else:
x = 700
y = 460
if x <= 900 and y <= 460:
x= x + 140
pyautogui.click(x,y)
time.sleep(0.001)
else:
x = 700
y = 520
if x <= 900 and y <= 520:
x= x + 1
pyautogui.click(x,y)
time.sleep(0.001)
else:
x = 700
y = 580
if x <= 900 and y <= 580:
x= x + 1
pyautogui.click(x,y)
time.sleep(0.001)
else:
x = 700
y = 600
if x <= 900 and y <=600:
x= x + 1
pyautogui.click(x,y)
time.sleep(0.001)
else:
print("finish")
PD: I know that my code is very weird, I put the if and the else conditions because I want to be sure that the program clicks by a horizontal mode, no in digonal, I'm new programming jeje.
A much simpler approach might be what you need. Create arrays of your x and y values, then a pair of for loops will build every point in your 200x200 rectangle and you can click at that point.
xs = range(700,700+200)
ys = range(400,400+200)
for x in xs:
for y in ys:
pyautogui.click(x,y)

Random Turtle movement, bound in window

Created the program to randomize the movement of the turtle but cannot get it to break the loop once it touches a boundary (window). Tried a few solutions posted with similar questions but still no luck.
from turtle import Turtle, Screen
import random
def createTurtle(color, width):
tempName = Turtle("turtle")
tempName.speed("fastest")
tempName.color(color)
tempName.width(width)
return tempName
def inScreen(screen, turt):
min_x, max_x = -wn.window_width() / 2 , wn.window_width() / 2
min_y, max_y = -wn.window_height() / 2 , wn.window_height() / 2
turtleX, turtleY = turt.pos()
while (min_x < turtleX < max_x) and (min_y < turtleY < max_y):
turt.left(random.randrange(360))
turt.fd(random.randrange(100))
turtleX, turtleY = turt.pos()
print(turtleX, ",", turtleY)
wn = Screen()
alpha = createTurtle("red", 3)
inScreen(wn, alpha)
wn.exitonclick()
The variables turtleX and turtleY are being used in your while condition, but you never reevaluate them within the loop.
This is why your print function only ever outputs 0.0 , 0.0

How to keep random walk scenario from going outside graphics window

I have created a random walk scenario where it takes one step in a random direction for a specific number of times. The one thing that I have run in to is that sometimes it will go off of the graphics window that I have set up and I can no longer see where it is at.
Here is the code:
from random import *
from graphics import *
from math import *
def walker():
win = GraphWin('Random Walk', 800, 800)
win.setCoords(-50, -50, 50, 50)
center = Point(0, 0)
x = center.getX()
y = center.getY()
while True:
try:
steps = int(input('How many steps do you want to take? (Positive integer only) '))
if steps > 0:
break
else:
print('Please enter a positive number')
except ValueError:
print('ERROR... Try again')
for i in range(steps):
angle = random() * 2 * pi
newX = x + cos(angle)
newY = y + sin(angle)
newpoint = Point(newX, newY).draw(win)
Line(Point(x, y), newpoint).draw(win)
x = newX
y = newY
walker()
My question is, Is there a way that I can set parameters on the graphics window so that the walker can not go outside the window? And if it tries to, it would just turn around and try another direction?
Try defining upper and lower bounds for x and y. Then use a while loop that keeps trying random points until the next one is in bounds.
from random import *
from graphics import *
from math import *
def walker():
win = GraphWin('Random Walk', 800, 800)
win.setCoords(-50, -50, 50, 50)
center = Point(0, 0)
x = center.getX()
y = center.getY()
while True:
try:
steps = int(input('How many steps do you want to take? (Positive integer only) '))
if steps > 0:
break
else:
print('Please enter a positive number')
except ValueError:
print('ERROR... Try again')
# set upper and lower bounds for next point
upper_X_bound = 50.0
lower_X_bound = -50.0
upper_Y_bound = 50.0
lower_Y_bound = -50.0
for i in range(steps):
point_drawn = 0 # initialize point not drawn yet
while point_drawn == 0: # do until point is drawn
drawpoint = 1 # assume in bounds
angle = random() * 2 * pi
newX = x + cos(angle)
newY = y + sin(angle)
if newX > upper_X_bound or newX < lower_X_bound:
drawpoint = 0 # do not draw, x out of bounds
if newY > upper_Y_bound or newY < lower_Y_bound:
drawpoint = 0 # do not draw, y out of bounds
if drawpoint == 1: # only draw points that are in bounds
newpoint = Point(newX, newY).draw(win)
Line(Point(x, y), newpoint).draw(win)
x = newX
y = newY
point_drawn = 1 # set this to exit while loop
walker()

How can I fill each petal separately using begin_fill()?

I have the following code that generates a petal pattern for a flower I'm trying to build. However, the problem is the fill part.
What should happen is each petal to be filled individually:
Instead, what happens is this:
import turtle
import math
wn = turtle.Screen()
wn.bgcolor("white")
def draw_leaf(turtle, side, theta = 0):
angle = 2
turtle.color("#67bd3c")
for x in range(-180,180):
y = math.sin(math.radians(angle))
angle += 1
y = y * side
x_axis = (x % 180) * math.cos(math.radians(theta)) + y * math.sin(math.radians(theta))
y_axis = (x % 180) * (-1 * (math.sin(math.radians(theta)))) + y * math.cos(math.radians(theta))
turtle.goto(-1 * x_axis, -1 * y_axis)
return
def draw_flower(turtle, petals):
for x in range(petals):
theta = 180/(petals - 1)
turtle.pendown()
turtle.begin_fill()
draw_leaf(turtle, 35, theta * x)
turtle.end_fill()
turtle.penup()
turtle.left(theta)
return
draw_flower(turtle,4)
wn.exitonclick()
It looks like each draw_leaf call begins when the turtle is at the far end of the leaf that it just previously drew. So the polygon that is filled during the current draw_leaf includes that end point. This is more apparent if you draw each leaf with a different color.
One possible solution is to goto the center of the flower after your penup, before you draw the next leaf.
def draw_flower(turtle, petals):
start = turtle.pos()
for x in range(petals):
theta = 180/(petals - 1)
turtle.pendown()
turtle.begin_fill()
draw_leaf(turtle, 35, theta * x)
turtle.end_fill()
turtle.penup()
turtle.goto(*start)
turtle.left(theta)
return

Categories