Drawing a chessboard with Turtle (even number dimension fail) - python

I have written this Python code with turtle graphics for drawing a chessboard by given dimension. The problem I'm facing is when I enter an odd number everything works just fine:
The last square is also filled, I just didn't manage to screen shot it on time
But when I enter an even number, it's like:
Here's the code:
from turtle import *
import sys
def main():
dimension = int(input('Enter dimension: '))
side = 50
x_coord = -250
y_coord = 300
turtle = Turtle()
turtle.speed('fastest')
turtle.pensize(5)
for i in range(dimension ** 2):
if not i % dimension:
y_coord -= side
turtle.penup()
turtle.setx(x_coord)
turtle.sety(y_coord)
turtle.pendown()
if not i % 2:
turtle.begin_fill()
for _ in range(4):
turtle.forward(side)
turtle.right(90)
turtle.forward(side)
turtle.end_fill()
if __name__ == '__main__':
sys.exit(main())

A similar flag-based solution with alternate approaches. I don't understand what your main() layout gets you so I reworked it to be a potential library with the test code under __main__:
import turtle
def draw_board(dimension, x_coord, y_coord, side):
parity = False
for i in range(dimension ** 2):
if i % dimension == 0:
y_coord -= side
turtle.penup()
turtle.setpos(x_coord, y_coord)
turtle.pendown()
parity = parity != (dimension % 2 == 0) # logical XOR
if parity:
turtle.begin_fill()
for _ in range(4):
turtle.forward(side)
turtle.right(90)
if turtle.filling():
turtle.end_fill()
turtle.forward(side)
parity = not parity
if __name__ == '__main__':
size = int(input('Enter dimension: '))
turtle.speed('fastest')
turtle.pensize(5)
draw_board(size, -250, 300, 50)
turtle.hideturtle()
turtle.exitonclick()

I didnt look through your code, but it seems that the problem you have is that unlike a true chessboard, you change from white to black and vice versa when making a new line of squares, this example:
black,white,black,white
black,white,black,white
etc.
or black,white,black
white,black,white
etc.
while a chessboard is:
black,white,black,white
WHITE,black,white,black
BLACK....etc.
you see the difference?
so that seems to be the problem, il try to fix your code aswell, but i think you could manage that

I suggest setting a flag for when to fill instead of doing it only when it's an odd number from the range which is what trips you up since it doesn't go black white left to right, it reaches then end an then goes right to left.
Anyway, here is my edit, just a simple boolean which toggles each time except when going to new row. I also suggest using turtle.exitonclick instead of sys.exit
from turtle import *
def main():
dimension = int(input('Enter dimension: '))
side = 50
x_coord = -250
y_coord = 300
turtle = Turtle()
turtle.speed('fastest')
turtle.pensize(5)
fill = False
for i in range(dimension ** 2):
if not i % dimension:
y_coord -= side
turtle.penup()
turtle.setx(x_coord)
turtle.sety(y_coord)
turtle.pendown()
if not dimension % 2:
fill = not fill
if fill:
turtle.begin_fill()
for _ in range(4):
turtle.forward(side)
turtle.right(90)
turtle.forward(side)
turtle.end_fill()
fill = not fill
if __name__ == '__main__':
main()
exitonclick()

For Python 3,7 I would recommend this way
import turtle
turtle.speed(0)
turtle.up()
turtle.goto(-200,200)
turtle.down()
for row in range(8):
for col in range(8):
if col % 2 == row % 2:
turtle.forward(50)
continue
turtle.begin_fill()
for _ in range(4):
turtle.forward(50)
turtle.right(90)
turtle.end_fill()
turtle.forward(50)
turtle.backward(400)
turtle.right(90)
turtle.forward(50)
turtle.left(90)
turtle.width(6)
for _ in range(4):
turtle.forward(400)
turtle.left(90)
turtle.hideturtle()
turtle.done()

Related

How do I make this a 6 sized snowflake instead of 8?

Not originally my code:
import turtle
wn = turtle.Screen()
wn.bgcolor('Black')
wn.setup( width = 250, height = 250)
turtle = turtle.Turtle()
def snowflake (size, pensize, x, y):
""" function that draws a snowflake """
turtle.speed(100)
turtle.penup()
turtle.goto(x, y)
turtle.forward(10*size)
turtle.left(45)
turtle.pendown()
turtle.color('white')
for x in range (8):
branch(size)
turtle.left(45)
def branch (size):
for z in range (3):
for z in range (3):
turtle.forward(10.0*size/3)
turtle.backward(10.0*size/3)
turtle.right(45)
turtle.left(90)
turtle.backward(10.0*size/3)
turtle.left(45)
turtle.right(90)
turtle.forward(10.0*size)
snowflake(8, 6, 0, 0)
wn.exitonclick()
If it's not originally your code, your should provide proper blame, I mean credit for it. The issue with this code is that the base angle 45 is being used to generate the 8-sided snowflake as well as the angle of the small branches. So when we go to use 60 for a 6-sided snowflake, it's hard to know which 45's (or 90's) to replace and which to keep. The author of the original code didn't help any by starting the branch logic in the snowflake() function, before calling the branch() function. So let's tease out the two different uses of 45 degrees, make the code more explicit, and switch just the sides to 60 degrees:
from turtle import Screen, Turtle
SIDES = 6
BRANCH_ANGLE = 45
def snowflake(size, x, y):
""" function that draws a snowflake """
turtle.penup()
turtle.goto(x, y)
turtle.forward(size)
turtle.left(BRANCH_ANGLE)
turtle.pendown()
for _ in range(SIDES):
branch(size)
turtle.left(BRANCH_ANGLE)
def branch(size):
for _ in range(3):
for _ in range(3):
turtle.forward(size / 3)
turtle.backward(size / 3)
turtle.right(BRANCH_ANGLE)
turtle.left(2 * BRANCH_ANGLE)
turtle.backward(size / 3)
turtle.left(BRANCH_ANGLE)
turtle.right(BRANCH_ANGLE + 360 / SIDES)
turtle.forward(size)
screen = Screen()
screen.bgcolor('black')
screen.setup(width=250, height=250)
turtle = Turtle()
turtle.color('white')
turtle.speed('fastest')
snowflake(80, 0, 0)
turtle.hideturtle()
screen.exitonclick()

Turtle code not working, showing py-lint no member error

i believe i have coded everything correctly but i keep getting an error message saying, for example("Module 'turtle' has no 'reset' member)
import turtle
color = input('Enter a color:')
while (color != "QUIT"):
turtle.reset()
turtle.pencolor(color)
turtle.pensize(10)
n = int(input('Enter a number:'))
if n % 3 == 0 and n % 5 == 0:
turtle.penup()
turtle.setposition(x=0, y=150)
turtle.pendown()
drawU(turtle.Turtle)
turtle.penup()
turtle.setposition(x = 0, y = -10)
turtle.pendown()
drawH(t)
elif n % 3 == 0:
turtle.penup()
turtle.setposition(x=0, y=150)
turtle.pendown()
drawU(turtle.Turtle)
elif n % 5 == 0:
turtle.penup()
turtle.setposition(x=0, y=150)
turtle.pendown()
drawH(turtle.Turtle)
else:
turtle.pencolor('black')
def drawU (t):
turtle.setheading(270)
turtle.forward(150)
turtle.left(90)
turtle.forward(75)
turtle.left(90)
turtle.forward(150)
each "turtle.____" shows as an error. i am not too sure what i am doing wrong. i included turtle.done() at the end as well, this is only half of my code.
i believe i have coded everything correctly
Far from it: termination of your loop depends on the value of color which never changes during the loop; you should be passing a turtle instance here drawU(turtle.Turtle) but are passing a turtle class; your else clause makes no sense, effectively a no-op; your indentation as shown doesn't work; your drawH() function is missing.
Below is my attempt to reconstruct your intended code, but I can't be certain:
from turtle import Screen, Turtle
def drawU(turtle):
turtle.setheading(270)
turtle.forward(150)
turtle.left(90)
turtle.forward(75)
turtle.left(90)
turtle.forward(150)
def drawH(turtle):
pass
color = input('Enter a color: ')
screen = Screen()
turtle = Turtle()
while color != "QUIT":
n = int(input('Enter a number: '))
turtle.reset()
turtle.pencolor(color)
turtle.pensize(10)
if n % 3 == 0 and n % 5 == 0:
turtle.penup()
turtle.setposition(x=0, y=150)
turtle.pendown()
drawU(turtle)
turtle.penup()
turtle.setposition(x=0, y=10)
turtle.pendown()
drawH(turtle)
elif n % 3 == 0:
turtle.penup()
turtle.setposition(x=0, y=150)
turtle.pendown()
drawU(turtle)
elif n % 5 == 0:
turtle.penup()
turtle.setposition(x=0, y=150)
turtle.pendown()
drawH(turtle)
color = input('Enter a color: ')
screen.mainloop()

Multiple Turtles, multiple random movements

I have an assignment where I have to make a game in python with turtles.
I am able to generate a grid like I want to, and I am able to generate multiple different turtles. my
- I have no clue where to start in terms of figuring out how to have each of my three different turtles each move throughout the board randomly, while staying on the grid line.
- the "game" must stop after two of the turtles have hit the edge of the screen, I do not know how to do this, either.
here is what I have so far:
import turtle
import random
turtle.pensize(2)
turtle.penup()
turtle.goto(-160,-160)
turtle.pendown()
turtle.color("green")
turtle.speed(0)
for i in range(4):
turtle.forward(320)
turtle.left(90)
for y in range(-160,160,80):
for x in range(-160,160,80):
turtle.penup()
turtle.goto(x,y)
turtle.pendown()
for k in range(4):
turtle.forward(40)
turtle.left(90)
turtle.end_fill()
for y in range(-120,160,80):
for x in range(-120,160,80):
turtle.penup()
turtle.goto(x,y)
turtle.pendown()
for k in range(4):
turtle.forward(40)
turtle.left(90)
billy = turtle.Turtle()
billy.shape("turtle")
billy.color("red")
billy.penup()
billy.left(90)
rick = turtle.Turtle()
rick.shape("turtle")
rick.color("orange")
rick.penup()
mike = turtle.Turtle()
mike.shape("turtle")
mike.color("purple")
mike.penup()
turtle.done()
strong guidance would be VERY helpful.
You could take advantage of object orientation. Here is my version of your turtle script:
import turtle
import random
# I added randint.
from random import randint
# Let's define a class so we can create turtles
class MyTurtle():
# Here's the constructor. Where we give some initial values.
def __init__(self, name, color):
self.name = name
self.color = color
self.turtle = turtle.Turtle()
self.turtle.shape("turtle")
self.turtle.color(self.color)
self.turtle.speed(1)
self.turtle.pd()
# We need to know if this turtle is off the board.
def off_board(self):
x = self.turtle.xcor()
y = self.turtle.ycor()
return x < -160 or 160 < x or y < -160 or 160 < y
# calling this will move the turtle in a random direction.
def move(self):
turn = randint(0,2)
if turn == 1:
self.turtle.lt(45)
elif turn == 2:
self.turtle.rt(45)
self.turtle.forward(5)
# Put your code for drawing the grid
# Let's create some turtles and start moving them.
turtles = []
turtles.append( MyTurtle('billy', 'red'))
turtles.append( MyTurtle('chris', 'blue'))
turtles.append( MyTurtle('lilly', 'pink'))
turtles.append( MyTurtle('kevin', 'green'))
ok = True
while ok:
for t in turtles:
t.move()
if t.off_board():
print ("Turtle %s wins!!!" % (t.name))
ok = False
turtle.done()
Come on! Just one upvote for this awesome turtle script?

Adding user checks to Python turtle tic-tac-toe game

import turtle
#1)draw board
sc= turtle.Screen()
sc.setup(300,300)
import turtle
sc= turtle.Screen()
sc.setup(300,300)
turtle.speed(0)
turtle.pensize(10)
turtle.bgcolor("black")
turtle.pencolor("white")
turtle.penup()
turtle.goto(-150,50)
turtle.pendown()
turtle.forward(300)
turtle.penup()
turtle.goto(-150,-50)
turtle.pendown()
turtle.forward(300)
turtle.penup()
turtle.goto(-50,150)
turtle.setheading(-90)
turtle.pendown()
turtle.forward(300)
turtle.penup()
turtle.goto(50,150)
turtle.pendown()
turtle.forward(300)
turtle.penup()
#2) X's and O's
turtle.pencolor("yellow")
def kreuz(x,y):
turtle.penup()
turtle.goto(x+30,y-45)
turtle.setheading(-45)
turtle.pendown()
turtle.forward(50)
turtle.penup()
turtle.goto(x+60,y-40)
turtle.setheading(-130)
turtle.pendown()
turtle.forward(50)
turtle.penup()
def kreis(x,y):
turtle.penup()
turtle.goto(x+50,y-80)
turtle.setheading(0)
turtle.pendown()
turtle.circle(20)
turtle.penup()
AlleTeile=["","","","","","","","",""]
nächsterZug="X"
def zeichneTeile (AlleTeile):
x = -150
y = 150
for einTeil in AlleTeile:
if einTeil=="X":
kreuz(x,y)
elif einTeil=="O":
kreis(x,y)
else:
print("leeres feld")
x=x+100
if x > 50:
x=-150
y=y-100
zeichneTeile(AlleTeile)
def geklickt(x,y):
global nächsterZug,AlleTeile
senkrecht= (x+150) // 100
waagrecht= (-y+150)// 100
Bereich= senkrecht+waagrecht*3
Bereich=int(Bereich)
print("Du klicktest auf Bereich-Nummer", Bereich)
AlleTeile[Bereich]=nächsterZug
if nächsterZug =="X":
nächsterZug="O"
else:
nächsterZug="X"
zeichneTeile(AlleTeile)
turtle.onscreenclick(geklickt)
turtle.mainloop()
I want to create this tic-tac-toe game using turtle in Python but I am stuck. The problem is that I keep drawing noughts and crosses on the game board after all 9 fields are full with noughts and crosses. How can I code this so that after 9 turns (9 fields) it is no longer possible to keep on drawing?
Since unused squares consist of an empty string in AlleTeile, this is trivial to fix since empty strings are False in a boolean context. At the top of geklickt(), after the global statement:
if all(AlleTeile):
print("All taken!")
return
We can reuse the same trick later in that function to prevent overwritting of existing squares. After the Bereich calculation, we can do something like:
print("Du klicktest auf Bereich-Nummer", Bereich, end="")
if AlleTeile[Bereich]:
print(" -- already taken!")
return
else:
print()
Here's my complete rework with the above changes, some turtle idoms, code cleanup and English translation courtesy of Google (and common sense):
from turtle import Screen, Turtle
# X's and O's
def cross(x, y):
turtle.penup()
turtle.goto(x + 30, y - 35)
turtle.setheading(-45)
turtle.pendown()
turtle.forward(50)
turtle.penup()
turtle.goto(x + 60, y - 30)
turtle.setheading(-130)
turtle.pendown()
turtle.forward(50)
turtle.penup()
def nought(x, y):
turtle.penup()
turtle.goto(x + 50, y - 70)
turtle.setheading(0)
turtle.pendown()
turtle.circle(20)
turtle.penup()
# Playing the game
def drawSquares():
screen.tracer(False) # because this routine is a graphics bottleneck
x, y = -150, 150
for square in AllSquares:
if square == "X":
cross(x, y)
elif square == "O":
nought(x, y)
x += 100
if x > 50:
x = -150
y -= 100
screen.tracer(True)
def clicked(x, y):
global turn
if all(AllSquares):
print("All taken!")
return
vertical = (x + 150) // 100
horizontal = (150 - y) // 100
Area = int(vertical + horizontal * 3)
print("You clicked area number", Area, end="")
if AllSquares[Area]:
print(" -- already taken!")
return
else:
print()
AllSquares[Area] = turn
if turn == "X":
turn = "O"
else:
turn = "X"
drawSquares()
# Draw the board
screen = Screen()
screen.setup(330, 330)
screen.bgcolor("black")
turtle = Turtle(visible=False)
turtle.pensize(10)
turtle.color("white")
turtle.speed('fastest')
turtle.penup()
turtle.goto(-150, 50)
turtle.pendown()
turtle.forward(300)
turtle.penup()
turtle.goto(-150, -50)
turtle.pendown()
turtle.forward(300)
turtle.setheading(-90)
turtle.penup()
turtle.goto(-50, 150)
turtle.pendown()
turtle.forward(300)
turtle.penup()
turtle.goto(50, 150)
turtle.pendown()
turtle.forward(300)
turtle.penup()
# Start the game
turtle.color("yellow")
AllSquares = ["", "", "", "", "", "", "", "", ""]
turn = "X"
drawSquares()
screen.onscreenclick(clicked)
screen.mainloop()

Using turtle to draw inputs in Python

I am working on a final project for python for my intro to python class. I have written code for each of the letters in the alphabet, my idea is to have the user input some words, and return code for all of the input letters. I have tried using a = code for turtle but this does not work. Any Ideas?
x = input()
codes = {'a': 'code for turtle',.....}
print(codes[str(x)])
Would a dictionary with an input() work?
Let's expand (and correct) #GerardAnthonyMcBride's dictionary-based approach. Here's an overly simplified example that just prints the letters 'S' and 'O':
from turtle import Turtle, Screen
SIZE = 100
def draw_O(turtle):
turtle.pendown()
for _ in range(4):
turtle.forward(SIZE)
turtle.left(90)
turtle.penup()
def draw_S(turtle):
position = turtle.position()
turtle.pendown()
turtle.forward(SIZE)
turtle.left(90)
turtle.forward(SIZE / 2)
turtle.left(90)
turtle.forward(SIZE)
turtle.right(90)
turtle.forward(SIZE / 2)
turtle.right(90)
turtle.forward(SIZE)
# leave turtle as we found it
turtle.penup()
turtle.setposition(position)
characters = {
'O': draw_O,
'S': draw_S,
}
screen = Screen()
yertle = Turtle()
string = input()
for character in string:
if character in characters:
characters[character](yertle)
yertle.forward(SIZE * 1.25)
screen.exitonclick()
OUTPUT

Categories

Resources