Making multiple turtles in one window - python

I want to make more than two turtles when I run the modules.
So I declared two variables on turtle but there's only one turtle I can see.
What's wrong with my code?
import turtle
t1=turtle.Turtle()
t2=turtle.Turtle()
colors = ["red", "blue", "green"]
turtle.bgcolor("yellow")
t1.speed(3)
t1.width(5)
length1 = 10
t2.speed(3)
t2.width(5)
length2 = 10
while length1 < 500:
t1.fd(length1)
t1.pencolor(colors[length1%3])
t1.right (89)
length1 += 3 #length1 = length1 + 3
while length2 < 500:
t2.fd(length2)
t2.pencolor(pink)
t2.left (89)
length2 += 4 #length2 = length2 + 4
input()

Your turtles are moving one by one. The first while loop does the job with t1, and when it's done, the second while will take care of t2. It's like "t1, make your first step. Then, t1, make your second. (and repeat this until length1 isn't less than 500 anymore.) Now t1 is done, so t2, make your first step. t2, your second step. (and it continues.)"
Instead, you want them to take turns making each of their steps. That's like "t1, make your first step. Then, t2, make your first. t1, make your second step. t2, your turn for your second step. (and it continues.)"
So your while loop should look like:
t1.pencolor(colors[length1 % 3])
t2.pencolor("pink")
while length1 < 500 or length2 < 500:
if length1 < 500:
t1.fd(length1)
t1.right(89)
length1 += 3 # length1 = length1 + 3
if length2 < 500:
t2.fd(length2)
t2.left(89)
length2 += 4 # length2 = length2 + 4
(Note you don't have to set the pencolor each time you move the turtle.)

there's only one turtle I can see
Is there literally only one turtle, or do you run out of patience waiting for the first turtle to finish before the second turtle starts (and breaks, due to the unquoted 'pink')? If this is about wanting to see both turtles in action at the same time, as folks have concluded, here's my approach:
Short of using threads, I use generators to allow the two turtles to run in a coroutine-like fashion. The advantage is that the turtles can share the exact same code, if they want to, or they can use completely different code. But it avoids duplicating code or maintaining unrelated code in the same while loop:
from turtle import Screen, Turtle
screen = Screen()
screen.bgcolor("yellow")
t1 = Turtle()
t1.pencolor('blue')
t2 = Turtle()
t2.pencolor('pink')
def pattern(turtle, increment, angle):
turtle.speed('fast')
turtle.width(5)
length = 10
while length < 500:
turtle.forward(length)
turtle.right(angle)
length += increment
yield 0
generator1 = pattern(t1, 3, 89)
generator2 = pattern(t2, 4, -89)
while next(generator1, 1) + next(generator2, 1) < 2:
pass
screen.exitonclick()

Related

Pygame Infinite World Generation Broken

So I'm making a basic 2D platformer game with the pygame module in python. Recently I've been trying to implement infinite world generation, but have been having some problems. The generation works fine, however, at the player's spawn, a bunch of random tiles spawn, obstructing the whole spawn area. I can't seem to find what's causing this.
Here's everything you need to replicate my situation:
map generation:
def generate_chunk(x,y):
chunk_data = []
for y_pos in range(CHUNK_SIZE):
for x_pos in range(CHUNK_SIZE):
target_x = x * CHUNK_SIZE + x_pos
target_y = y * CHUNK_SIZE + y_pos
tile_type = 0 # nothing
if target_y > 10:
tile_type = 2 # dirt
elif target_y == 10:
tile_type = 1 # grass
elif target_y < 10:
tile_type = 0
if tile_type != 0:
chunk_data.append([[target_x,target_y],tile_type])
return chunk_data
...
while True:
...
tile_rects = []
for y in range(3):
for x in range(4):
target_x = x - 1 + int(round(scroll[0]/(CHUNK_SIZE*16)))
target_y = y - 1 + int(round(scroll[1]/(CHUNK_SIZE*16)))
target_chunk = str(target_x) + ';' + str(target_y)
if target_chunk not in game_map:
game_map[target_chunk] = generate_chunk(target_x,target_y)
for tile in game_map[target_chunk]:
display.blit(tile_index[tile[1]],(tile[0][0]*16-scroll[0],tile[0][1]*16-scroll[1]))
if tile[1] in [1,2]:
tile_rects.append(pygame.Rect(tile[0][0]*16,tile[0][1]*16,16,16))
full code:
https://github.com/nice-404/Platformer
I can't seem to figure out what is causing the random tile spawning.
(I have been following DaFluffyPotato's platformer tutorial series because I am new to pygame)
After 2 weeks of debugging and further looking into the chunk generating code, I couldn't find out anything. However, I did figure out that the issue only happened in a small area, at the 0 x value. So what I did was I made the player spawn very far away from this, and made a boundary so that it couldn't walk far enough to see the issue. Not really fixing the issue, but at least it works now.

I used return, however the recursion does not end. help me please

I am doing a question that gives me a start coordinate, a end coordinate and the number of times of moving.Every time you can add 1 or minus 1 to x or y coordinate based on previous coordinate and the number of moving limit the time the coordinate can move. At last, I need to identify whether there is a possibility to get to the end coordinate
I decide to use recursion to solve this problem however, it does not end even if I wrote return inside a if else statement. Do you mind to take a look at it.
This is the code
# https://cemc.uwaterloo.ca/contests/computing/2017/stage%201/juniorEF.pdf
# input
start = input()
end = input()
count = int(input())
coo_end = end.split(' ')
x_end = coo_end[0]
y_end = coo_end[1]
end_set = {int(x_end), int(y_end)}
#processing
coo = start.split(' ')
x = int(coo[0])
y = int(coo[1])
change_x = x
change_y = y
sum = x + y+count
set1 = set()
tim = 0
timer = 0
ways = 4** (count-1)
def elit(x, y, tim,timer, ways = ways):
print(tim,timer)
tim = tim +1
co1 = (x, y+1)
co2 = (x+1, y)
co3 = (x, y-1)
co4 = (x-1, y)
if tim == count:
tim =0
set1.add(co1)
set1.add(co2)
set1.add(co3)
set1.add(co4)
print(timer)
timer = timer +1
if timer == ways:
print('hiii')
return co1, co2, co3, co4 #### this is the place there is a problem
elit(co1[0],co1[1],tim,timer)
elit(co2[0],co2[1],tim,timer)
elit(co3[0],co3[1],tim, timer)
elit(co4[0],co4[1],tim, timer)
#print(elit(change_x,change_y,tim)) - none why
elit(change_x,change_y,tim, timer)
#print(list1)
for a in set1:
if end_set != a:
answer = 'N'
continue
else:
answer = "Y"
break
print(answer)
In addition, if you have any suggestions about writing this question, do you mind to tell me since I am not sure I am using the best solution.
one of example is
Sample Input
3 4 (start value)
3 3 (end value)
3 (count)
Output for Sample Input
Y
Explanation
One possibility is to travel from (3, 4) to (4, 4) to (4, 3) to (3, 3).
the detailed question can be seen in this file https://cemc.uwaterloo.ca/contests/computing/2017/stage%201/juniorEF.pdf
It is question 3. Thank you
thank you guys
the function is returning properly however by the time you reach the recursive depth to return anything you have called so many instances of the function that it seems like its in an infinite loop
when you call elite the first time the function calls itself four more times, in the example you have given timer is only incremented every 3 cycles and the function only return once timer hits 16 thus the function will need to run 48 times before returning anything and each time the function will be called 4 more times, this exponential growth means for this example the function will be called 19807040628566084398385987584 times, which depending on your machine may well take until the heat death of the universe
i thought i should add that i think you have somewhat over complicated the question, on a grid to get from one point to another the only options are the minimum distance or that same minimum with a diversion that must always be a multiple of 2 in length, so if t the movement is at least the minimum distance or any multiple of 2 over the result should be 'Y', the minimum distance will just be the difference between the coordinates on each axis this can be found by add in the difference between the x and y coordinates
abs(int(start[0]) - int(end[0])) + abs(int(start[1]) -int(end[1]))
the whole function therefore can just be:
def elit():
start = input('start: ').split(' ')
end = input('end: ').split(' ')
count = int(input('count: '))
distance = abs(int(start[0]) - int(end[0])) + abs(int(start[1]) -int(end[1]))
if (count - distance) % 2 == 0:
print('Y')
else:
print('N')
input:
3 4
3 3
3
output:
Y
input:
10 4
10 2
5
output:
N

Cleaning While Loop for Maya Python Study

I made a while loop for Maya python study. It works well, but it is redundant and I think there must be a way to shorten them better or make it looks good. Can you guys give me a suggestion about what I should do? Do you think using another def function would be better than this?
def addWalls(self, length, width, floorNum, bboxScale):
# count variables
count = 1
floorCount = 1
# length loop
while count < length:
# Adding floors on wall
while floorCount < floorNum:
cmds.duplicate(instanceLeaf=True)
cmds.xform(relative=True, translation=[0, 0, bboxScale[2]])
floorCount += 1
floorCount = 1
# Adding next wall
cmds.duplicate(instanceLeaf=True)
cmds.xform(relative=True, translation=[0, -bboxScale[1], -bboxScale[2] * (floorNum - 1)])
count += 1
# Final adding floors
if count == length:
while floorCount < floorNum:
cmds.duplicate(instanceLeaf=True)
cmds.xform(relative=True, translation=[0, 0, bboxScale[2]])
floorCount += 1
floorCount = 1
When I run your script it creates a grid of objects like this:
So if all it needs to do is make a grid of objects then your assumption is right, it makes no sense using a while loop. In fact it's really easy to do it with 2 for loops that represent the "wall's" width and height:
import maya.cmds as cmds
spacing = 5
width_count = 15
height_count = 15
for z in range(width_count):
for y in range(height_count):
cmds.duplicate(instanceLeaf=True)
cmds.xform(ws=True, t=[0, y * spacing, z * spacing])
It will yield the same result with a much shorter and readable script. If you want more flexibility in there it would only take simple tweaks.

Python - can't make number in variable higher

I'm programming game pong in python and I wan't the ball to be faster everytime it bounces of a bat. So I tried to add
global SPEED
SPEED + 25
into a function higher_speed which will trigger everytime when the ball bounces of the bat.
short version of game code here:
...
BALL_SIZE = 20
BAT_WIDTH = 10
BAT_HEIGHT = 100
SPEED = 250 # (in pixels per second)
BAT_SPEED = SPEED * 1.5 # (in pixels per second)
...
def higher_speed(SPEED, x):
x = 25
global SPEED
SPEED + x
return SPEED
# bounce left
if ball_position[0] < BAT_WIDTH + BALL_SIZE / 2:
if bat_min < bat_position[0] < bat_max:
# bat bounces ball
BALL_SPEED[0] = abs(BALL_SPEED[0])
global SPEED
higher_speed()
else:
# bat hadn't bounced the ball, player loses
score[1] += 1
reset()
# bounce right
if ball_position[0] > WIDTH7777 - (BAT_WIDTH + BALL_SIZE / 2):
if bat_min < bat_position[1] < bat_max:
BALL_SPEED[0] = -abs(BALL_SPEED[0])
higher_speed()
else:
score[0] += 1
reset()
...
Please help. I appreciate your time :).
Several things here:
First of all, the value is not being changed because it is not assigned in the first place, your function should look like this:
def higher_speed(SPEED, x):
x=25
global SPEED
SPEED += x
Second, if you're overwriting x at the beginning of the function and using SPEED as global, why pass it?:
def higher_speed():
global SPEED
SPEED += 25
Third, according to Python's PEP8 standards, capitalized words are only for constants, it would be a good use to the speed increase, so it should look like this:
SPEED_INCREASE = 25
def higher_speed():
global speed
speed += SPEED_INCREASE
And last, in general is a bad idea using global variables you can check this article or google it, so try to avoid it, then it should look like this:
def higher_speed(speed):
return speed+SPEED_INCREASE
speed = higher_speed(speed)
or you could set this inline:
speed += SPEED_INCREASE
I hope it helped!

python turtle graphics iterating through color index throwing an error

I've just started with pythons Turtle graphics module, and I'm running into an issue not with Turtle itself I don't think, but my algorithm styling. I'm using the window.colormode(255) which is awesome and working great when I iterate from red to blue in my program, incrementing the blue variable and decrementing the red variable once every loop.
I'm running into a problem with my filter that should reverse the order of the color incrementor/decrementor (i want to go from blue back to red once r = 0 and b = 255):
Here's the code to draw:
counter = 1
firstlength = 1
secondlength = 1
thirdlength = 1
fourthlength = 1
fifthlength = 1
colorList = [255,0,0] # r g b
f = 0 # index for colorlist
for i in listOfTurtles:
i = turtle.Turtle()
i.pencolor(colorList[0], colorList[1], colorList[2])
i.speed(0) # no turn animations
i.left(counter)
i.forward(firstlength)
i.left(15)
i.forward(secondlength)
i.left(15)
i.forward(thirdlength)
i.left(15)
i.forward(fourthlength)
i.left(15)
i.forward(fifthlength)
counter += 1
firstlength += .1
secondlength += .11
thirdlength += .12
fourthlength += .13
fifthlength += .14
Here's the problem with iterating through the pen color (using an answer below):
blueUp = True
if blueUp == True:
colorList[0] -= 1
colorList[2] += 1
if colorList[0] <= 1:
blueUp = False
else:
colorList[0] += 1
colorList[2] -= 1
if colorList[2] <= 0:
blueUp = True
however, this filter I've set up isn't flipping the color incrementor/decrementor when it needs to; thus resulting in a "bad color sequence error: (-1, 0, 256)
So I know its incrementing my blue 1 digit too high, and my red one too low on the first pass and then erroring out, but I'm unsure how to fix it. I've played with the > values and made them higher (to catch around 5 or 250) but I'm not getting results.
I'm totally open to a completely different way to write this, as I'm sure I've thought up the worst possible way to solve this issue.
For starters, you should probably change this:
if blueUp == False:
if colorsList[2] > 0:
to this:
if blueUp == False:
if colorList[2] > 1:
I'm an idiot. My bool variable was local to my outer for statement, the one iterating through my i's. every loop it would reset the value of blueUp and force the index down again by 1. Resolved the issue by moving my bool outside my outer for loop.

Categories