I need to make a code in python that draws the output below using recursion and a function named drawpoly. drawpoly() will take 6 arguments which include a turtle, the length of a side, the number of sides, red, green & blue. While the number of sides is > 2, drawpoly() will recursively call itself decrementing the number of sides by 1 each call. Red will increment by 10, green by 25 & blue by 35 each call. I need to set fillcolor and begin and end fill. I will also need will need to set the screen colormode to be able to use integers to make your colors.
[![enter image description here][1]][1]
her's the code I have so far It doesn't print out anything but its a rough outline of what I need to use in the program
wn = trtl.Screen()
def drawpoly(trtl, num_sides, side_length,color):
numOfSides=8
num_sides=8
side_length=100
color="blue"
while (numOfSides >2):
trtl.drawpoly(trtl,num_sides,side_length,color)
numOfSides -=1
def main():
return drawpoly
main()
[1]: https://i.stack.imgur.com/65dS4.png
Related
This question already has answers here:
What would be the output of range(x, y) if x > y?
(3 answers)
Closed last year.
I'm trying to load images in PyGame based on a value, like when the value is 6 it sets the image to be image number 6.
def bar():
global ink
global screen
global barImg
ink = 0
for ink in range(0,100):
barImg = pygame.image.load(f'inkbar\load{ink}.png')
screen.blit(barImg,(100,100))
pygame.display.update()
The value of ink gets changed in another function and I know that part works. Each image is called load0.png, load1.png and so on until 100, but the image never appears on the screen. I have tested putting the image on the screen by commenting out the for loop and just setting barImg to a specific image and it did put the image on the screen.
px, py = pygame.mouse.get_pos()
if pygame.mouse.get_pressed() == (1,0,0):
pygame.draw.rect(screen, (255,255,255), (px,py,10,10))
ink+=0.5
math.ceil(ink)
print(ink)
this is part of a function that allows the user to draw. This part detects mouse click and increases the value of ink. I tried calling bar() underneath the ink increase, but that decreased the rate of drawing.
I have removed the function bar()
ink+=1
math.ceil(ink)
print(ink)
for ink in range(1,100):
barImg = pygame.image.load(f'inkbar\load{ink}.png')
screen.blit(barImg,(100,100))
This is what I have used as a replacement, but now ink does not increase by one, it goes from 1 to 100 immediately, and causes large amounts of lag.
Maybe the images having "load" in the name is messing with something?
I have some code for running through frames of an animation which I know works
The code:
frame_index += animation_speed
if frame_index >= len(animation):
self.frame_index = 0
image = pygame.image.load(f'Ink ({int(frame_index)}).png')
screen.blit(image, (0,0))
pygame.display.update()
Essentially you want to have two variables, a frame index and an animation speed. The index is the number of the first image you are loading. In this case Ink 0.png or whatever it's called. So your frame index will be 0. This will increment by your animation speed variable. The higher this is, the faster your animation will be. The lower, the slower. After it loops it will go back to 0 if thats what you want. If you don't want that then you can simply remove the if statement.
Also check that you aren't filling the screen AFTER doing this as whatever you're wanting to see will just be covered instantly. Let me know if this works.
So I had to get familiar with turtle for a project with school. I got basically everything my professor asked besides for overlapping the squares.
However he would like the squares to overlap like this
I haven't been able to replicate this at all. I am wondering if their is something I need to throw into my code to easily solve it.
Here is my code
import turtle #Imports the 'turtle module' which allows intricate shapes and pictures to be drawn
my_turtle_pos = (10 , 10)
def square(my_turtle,x,y,length) : #I set up a function that helps me determine the square
my_turtle.penup() #Picks 'up' the turtle pen
my_turtle.setposition(x-length/2,y-length/2) #Helps set positon
my_turtle.pendown() #Puts 'down' the turtle pen
my_turtle.color('black','red') #Allows black outline, with red filling
my_turtle.begin_fill() #Starts the filling of red and helps remember the starting point for a filled area
my_turtle.forward(length) #Moves the turtle by the specified amount 'length'
my_turtle.left(90) #Moves the turtle by given amount '90'
my_turtle.forward(length)
my_turtle.left(90)
my_turtle.forward(length)
my_turtle.left(90)
my_turtle.forward(length)
my_turtle.left(90)
my_turtle.end_fill() #Stops filling with red, which will close with the current color
def graphic_pattern(my_turtle,x,y,length,times): #recursive function
if times <= 0: #This just tells us how many 'times' it needs to repeat till given amount
return
newSize = length/2.2 #This will grab the new size
graphic_pattern(my_turtle,x-length/2,y-length/2,newSize,times-1) #Functions to help with writing 'smaller' squares
graphic_pattern(my_turtle,x-length/2,y+length/2,newSize,times-1)
graphic_pattern(my_turtle,x+length/2,y-length/2,newSize,times-1)
graphic_pattern(my_turtle,x+length/2,y+length/2,newSize,times-1)
square(my_turtle,x,y,length)
my_turtle = turtle.Turtle(shape="arrow") #You can use differen't shapes for the turtle, I chose arrow, though the turtle was cool :)
my_turtle.speed(100) #I am not sure how fast the turtle can go, I just chose 100 cause it went by quicker.
graphic_pattern(my_turtle,3,0,300,4) #Example pattern stated from homework assignment.
I think it's something to do with where the pen draws the squares first. Thanks for any input!
Sounds like it's a simple sequencing of your graphic_pattern() and square() methods. It seems you would want to draw the top right graphic_pattern() first, followed by the middle square, and then followed by the rest of the graphic_pattern() calls:
import turtle #Imports the 'turtle module' which allows intricate shapes and pictures to be drawn
my_turtle_pos = (10 , 10)
def square(my_turtle,x,y,length) : #I set up a function that helps me determine the square
my_turtle.penup() #Picks 'up' the turtle pen
my_turtle.setposition(x-length/2,y-length/2) #Helps set positon
my_turtle.pendown() #Puts 'down' the turtle pen
my_turtle.color('black','red') #Allows black outline, with red filling
my_turtle.begin_fill() #Starts the filling of red and helps remember the starting point for a filled area
my_turtle.forward(length) #Moves the turtle by the specified amount 'length'
my_turtle.left(90) #Moves the turtle by given amount '90'
my_turtle.forward(length)
my_turtle.left(90)
my_turtle.forward(length)
my_turtle.left(90)
my_turtle.forward(length)
my_turtle.left(90)
my_turtle.end_fill() #Stops filling with red, which will close with the current color
def graphic_pattern(my_turtle,x,y,length,times): #recursive function
if times <= 0: #This just tells us how many 'times' it needs to repeat till given amount
return
newSize = length/2.2 #This will grab the new size
graphic_pattern(my_turtle,x+length/2,y+length/2,newSize,times-1)
square(my_turtle,x,y,length)
graphic_pattern(my_turtle,x-length/2,y-length/2,newSize,times-1)
graphic_pattern(my_turtle,x-length/2,y+length/2,newSize,times-1)
graphic_pattern(my_turtle,x+length/2,y-length/2,newSize,times-1)
my_turtle = turtle.Turtle(shape="arrow") #You can use differen't shapes for the turtle, I chose arrow, though the turtle was cool :)
my_turtle.speed(100) #I am not sure how fast the turtle can go, I just chose 100 cause it went by quicker.
graphic_pattern(my_turtle,3,0,300,4) #Example pattern stated from homework assignment.
You have to change the visit order of your recursive calls.
Now the order is post-order (visit all children, then visit the node).
With this particular order (visit upper right child, visit the node, visit the remaining children):
def graphic_pattern(my_turtle,x,y,length,times): #recursive function
if times <= 0: #This just tells us how many 'times' it needs to repeat till given amount
return
newSize = length/2.2 #This will grab the new size
graphic_pattern(my_turtle,x+length/2,y+length/2,newSize,times-1)
square(my_turtle,x,y,length)
graphic_pattern(my_turtle,x-length/2,y-length/2,newSize,times-1) #Functions to help with writing 'smaller' squares
graphic_pattern(my_turtle,x-length/2,y+length/2,newSize,times-1)
graphic_pattern(my_turtle,x+length/2,y-length/2,newSize,times-1)
you can obtain the desired pattern.
In this code I can't see why it isn't printing a hexagon 24 times. I tell it to make a 6 sided shape with 60 degrees between lines ( a hexagon) and tell it do turn 15 degrees each time. This ends up being a even 24 for the picture I'm trying to draw.
import turtle
Hex_Count = 0
x = turtle.Turtle()
x.speed(.25)
def Hexagon():
for i in range(24):
for i in range(6):
x.forward(100)
x.left(60)
Hex_Count = Hex_Count + 1
x.left(15)
print(Hex_Count)
Hexagon
But, for some reason, when I run this code the turtle screen pops up for about a half second then closes. How do I get it to perform in the way I want it to?
You have several errors that I corrected for you; I added the explanation in the comments:
import turtle
hexagons_count = 0
my_turtle = turtle.Turtle() # x is not a good name for a Turtle object
# my_turtle.speed(.25) # see #cdlane comment reported in a note under.
def draw_hexagon(): # use explicit names respecting python conventions (no camel case)
global hexagons_count # need global to modify the variable in the function scope
for idx in range(24): # use different dummy variable names in your loops
for jdx in range(6): # use different dummy variable names in your loops
my_turtle.forward(100)
my_turtle.left(60)
hexagons_count += 1
my_turtle.left(15)
print(hexagons_count)
draw_hexagon() # need parenthesis to call the function
turtle.exitonclick() # this to exit cleanly
Note: I know you simply copied it from the OP but my_turtle.speed(.25)
doesn't make sense as the argument should be an int from 0 to 10 or a
string like 'slow', 'fastest', etc. I especially don't understand why
beginners with turtle code that isn't working call turtle.speed() at
all -- it seems to me a function to be tweaked after everything is
working. #cdlane
You have some reference issue, you just need to put the variable hex_count where it needs to be so you don't have error accessing it.
import turtle
x = turtle.Turtle()
x.speed(.25)
def Hexagon():
Hex_Count = 0
for i in range(24):
for i in range(6):
x.forward(100)
x.left(60)
Hex_Count += 1
x.left(15)
print(Hex_Count)
Hexagon()
prints 24
You have several problems with your program. One is that it will when after running through the program, closing the window it created. You can add turtle.exitonclick() to the end of your script which tells python to wait for a click in the graphics window, after which it will exit.
The second problem is that you don't call the Hexagon function because you're missing the parentheses. Even if a function takes no arguments, you still need to call it like:
Hexagon()
The final problem is that you need to define Hex_Count before you try to increment it. Hex_Count + 1 will thrown an error if Hex_Count wasn't already assigned to. You can fix this by putting
Hex_Count = 0
before your for loop in Hexagon.
An approach different in a lot of the details but primarily in its use of circle() to more rapidly draw the hexagons:
from turtle import Turtle, Screen # force object-oriented turtle
hex_count = 0 # global to count all hexagons drawn by all routines
def hexagons(turtle):
global hex_count # needed as this function *changes* hex_count
for _ in range(24): # don't need explicit iteration variable
turtle.circle(100, steps=6) # use circle() to draw hexagons
turtle.left(15) # 24 hexagons offset by 15 degrees = 360
hex_count += 1 # increment global hexagon count
print(hex_count)
screen = Screen()
yertle = Turtle(visible=False) # keep turtle out of the drawing
yertle.speed('fastest') # ask turtle to draw as fast as it can
hexagons(yertle)
screen.exitonclick() # allow dismiss of window by clicking on it
I am currently in the process of making a new cannon game. How can I make it so that there is just one cannon, on the bottom left hand of the screen?
from graphics import *
from math import sqrt
from math import trunc
def PinR(p,r):
if p.getX()>=r.getP1().getX() and p.getX()<=r.getP2().getX()and p.getY()>=r.getP1().getY() and p.getY()<=r.getP2().getY():
return True;
else:
return False;
def distance(p1,p2):
dx=p1.getX()-p2.getX();
dy=p1.getY()-p2.getY();
dist=sqrt(dx*dx+dy*dy);
return dist;
#parameter
FieldWidth=700;
FieldHeight=700;
GroundDepth=75;
BallSize=10;
OriginalSpeed=4;
FieldBackground="brown";
FieldBorder="brown";
tickLength=800000;
buttonSize=8;
# number of cannons and balls
numBalls=4;
# initial cannon power
explosionStrength=30;
# intial gravitational constant
g=1;
# clock tick delay
delay=0.05;
#Create field
Field=GraphWin("B",FieldWidth,FieldHeight);
Field.setBackground(FieldBackground);
#set of balls
spacing=FieldWidth/(numBalls);
ball=[];
for b in range (0,numBalls):
newball=Circle(Point(spacing*b+spacing//2,FieldHeight-GroundDepth),BallSize);
newball.setFill("black");
newball.draw(Field);
ball.append(newball);
#cannon
cannon=[]
for c in range (0,numBalls):
newCannon=Rectangle(Point(spacing*c+spacing//2-BallSize,FieldHeight-GroundDepth-BallSize*5),
Point(spacing*c+spacing//2+BallSize,FieldHeight-GroundDepth+BallSize));
newCannon.setFill("black");
newCannon.draw(Field);
cannon.append(newCannon);
#set of button groups (fire, powerup, powerdown)
fire=[];
for f in range (0,numBalls):
newbutton=Rectangle(Point(spacing*f+spacing//2-buttonSize//2,FieldHeight-GroundDepth-BallSize),
Point(spacing*f+spacing//2+buttonSize//2,FieldHeight-GroundDepth-BallSize+buttonSize));
newbutton.setFill("red");
newbutton.draw(Field);
fire.append(newbutton);
#wall
#target(red,white,red,white)
balldistance=20;
ball1=Circle(Point(FieldWidth//2-20,FieldHeight//2+20),BallSize);
ball1.setFill("red");
ball1.draw(Field);
The reason you get 4 cannons is that you're doing this:
for c in range (0,numBalls):
… where numBalls is 4, and you create a new cannon each time through the loop.
Presumably with only 1 cannon you also only want one cannon ball and one shot, so just set numBalls = 1 instead of numBalls = 4.
However, it might make more sense to simplify the program while you're at it. Replace the lists of 4 cannons with a single cannon, get rid of the loop, do the same for the 4 balls, etc. Then you can also simplify the layout rules—no need for a spacing variable to configure how far apart the cannons are if there's only 1 of them. And so on. This might make it easier for you to understand how the program works—and figuring out how to simplify it might similarly be beneficial on its own.
And if you want to change its position, that's being set in this line:
newCannon=Rectangle(Point(spacing*c+spacing//2-BallSize,FieldHeight-GroundDepth-BallSize*5),
Point(spacing*c+spacing//2+BallSize,FieldHeight-GroundDepth+BallSize));
So, you can tweak the various constants (which all seem to have pretty reasonable names) to get the result you want—or, of course, just hardcode the position you want instead of calculating it.
I'm trying to leave one third of the image stock, change all the black to yellow in the middle, and change the bottom third black to blue. I know how to change the colours, the problem I'm facing is I'm unaware of how I can select only one third of the pixels to manipulate them. Here s what I have..
def changeSpots1():
file = pickAFile()
picture = makePicture(file)
show(picture)
pix = getAllPixels(picture)
for p in pix:
intensity = (getRed(p) + getGreen(p) + getBlue(p))
c = getColor(p)
if (intensity < 150):
newColour = setColor(p, yellow)
repaint(picture)
I am using a program called JES to write this, incase you're wondering about commands like pickAFile.
Thank you for any help!
I know nothing about JES, but I'm going to guess that getAllPixels returns the pixels in the usual order: the first row, then the next row, then the next, etc.
If so:
pix = getAllPixels(picture)
third = len(pix) // 3
for p in pix[:third]:
# do top-third stuff
for p in pix[third:third*2]:
# do middle-third stuff
for p in pix[third*2:]:
# do bottom-third stuff
This does assume that the picture s divisible perfectly into thirds. If it's not, you will need to know the picture's width so you can round to the nearest complete row (because otherwise the top third might actually be 250 complete rows and the first 47 pixels of the 251st, which won't look very good). I don't know what function JES has to get the width, but I'm sure it's simple.