Python Forum
Python 25 Line Challenge
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python 25 Line Challenge
#11
13 lines. I really not like lines being over 80 - 100 characters but, it works
from turtle import Turtle, Screen, colormode
from random import randint
class Turtles(Turtle):
    def __init__(self):
        super().__init__()
        self.speed('fastest'), self.shapesize(5), colormode(255), Screen(), Screen().onclick(self.click), self.ondrag(self.draw), Screen().onkey(self.colors, 'c'), Screen().listen(), Screen().mainloop()
    def colors(self):
        self.color((randint(0, 255), randint(0, 255), randint(0, 255)))
    def click(self, x, y):
        self.penup(), self.goto(x,y), self.pendown()
    def draw(self, x, y):
        self.ondrag(None), self.goto(x, y), self.ondrag(self.draw, btn=1)
Turtles()
I welcome all feedback.
The only dumb question, is one that doesn't get asked.

My Scripts
CookBook - Shmup - PyQt5 Music Player


Reply
#12
One more. Change background color with button click in tkinter.

import tkinter as tk
from random import randint
def rgb(label):
    color = tuple(randint(0, 255) for i in range(3))
    label['bg'] = f'#%02x%02x%02x' % color
root = tk.Tk()
label = tk.Label(root, width=50, height=20, relief='groove')
label.pack(padx=5, pady=4)
button = tk.Button(root, text='change color', command=lambda:rgb(label)).pack(expand=True, fill='both', padx=5, pady=4)
root.mainloop()
I welcome all feedback.
The only dumb question, is one that doesn't get asked.

My Scripts
CookBook - Shmup - PyQt5 Music Player


Reply
#13
(May-06-2022, 07:33 PM)menator01 Wrote: One more.

All right Menator01, I've got one for you. Since you seem to like a challenge I off you this one. It is the classic turtle race example that I have expanded to show a practical use for arrays. Can you get this one down below 25 lines?

#Turtle race - An example of using all of the topics
#with an introduction to using lists

from turtle import *
from random import *

turtlecnt = 10                     #number of turtles in the race
linetop = turtlecnt * 30 / 2       #location of top line
linebottom = 0 - linetop - 30      #location of bottom line
hideturtle()                       #setup the screen
penup()
speed("fastest")
goto(-200,linetop)
pendown()
goto(-200,linebottom)
penup()
goto(200,linetop)
pendown()
goto(200,linebottom)

racers = []                         #a list to hold our turtles

for i in range(0,turtlecnt):        #for each position in the list 
    newturtle = Turtle()            #create the turtle 
    racers.append(newturtle)        #add it to the turtle list

#a list of colors to randomly choose from
colors = ["yellow", "gold", "orange", "red", "maroon", "violet", "pink", "magenta",
          "purple", "navy", "blue", "skyblue", "cyan", "turquoise", "lightgreen",
          "green", "darkgreen", "chocolate", "brown", "gray", "black"]

#Setup the turtles
for i in range(0,turtlecnt):           #for each turtle in the list
    clrnum = randint(0,len(colors)-1)  #choose a random color
    racers[i].color(colors[clrnum])    #set the turtle to the color
    colors.pop(clrnum)                 #remove the color from the list (avoid repeats)
    racers[i].shapesize(2)             #increase the turtles size
    racers[i].penup()                  #no drawing during the race
    racers[i].goto(-200, (i * 30) - (turtlecnt * 30 / 2)) #goto the starting line
    racers[i].speed("fastest")         #set the speed (same as 0)
    
#repeat until on of the turtles reaches the finish line
racing = True                       #the race is running
i = 0                               #start at the first turtle
tracer(0)                           #do not automatically update window
while racing:                       #while the race is running
    racerdist = randint(0,5)        #choose a random distance to travel
    racers[i].forward(racerdist)    #for the current turtle, move the random distance
    if racers[i].xcor() >= 200:     #check if that move won the race
        racing = False              #the race is over
        winpos = i                  #this turtle won
        
    i = i + 1                       #setting up for the next turtle
    if i >= turtlecnt:              #have we reached the end of the turtle list?
        i = 0                       #yes? wrap to the beginning
    update()                        #manually update the window (needed when tracer is 0)

penup()                             #relocate the default turtle
goto(-200,racers[winpos].ycor())    #display the winner
write("The winner is turtle " + str(winpos),font=("",25,""))
Reply
#14
And here is another offering of my own -- I took the random maze idea from youTube's 8-bit guy and combined it with a random maze idea of my own. I had to do a little research as I've never had a reason to use the single line if/else before (as a teacher, readability is important).

from random import randint        
if randint(0,1) == 0:                
    cnt = 0
    while True:                       
        str = "/" if randint(0,1) == 0 else "\\"
        print(str,end="") 
        cnt = cnt + 1          
        if cnt % 80 == 0: print()      
else:                           
    flag = 0                    
    rooms = 30                 
    while True:                
        flag = 1 if flag == 0 else 0           
        print("|",end="")       
        for i in range(0,rooms):
            wall = randint(0,1) 
            if flag == 0:
                str = "--+" if wall == 0 else "  +"
            else:
                str = "  |" if wall == 0  or i == rooms - 1 else "   "
            print(str,end="")
        print("")
Reply
#15
(May-09-2022, 12:17 PM)codingCat Wrote: And here is another offering of my own -- I took the random maze idea from youTube's 8-bit guy and combined it with a random maze idea of my own. I had to do a little research as I've never had a reason to use the single line if/else before (as a teacher, readability is important).

from random import randint        
if randint(0,1) == 0:                
    cnt = 0
    while True:                       
        str = "/" if randint(0,1) == 0 else "\\"
        print(str,end="") 
        cnt = cnt + 1          
        if cnt % 80 == 0: print()      
else:                           
    flag = 0                    
    rooms = 30                 
    while True:                
        flag = 1 if flag == 0 else 0           
        print("|",end="")       
        for i in range(0,rooms):
            wall = randint(0,1) 
            if flag == 0:
                str = "--+" if wall == 0 else "  +"
            else:
                str = "  |" if wall == 0  or i == rooms - 1 else "   "
            print(str,end="")
        print("")

Hello,

from random import randint        
if randint(0,1) == 0:                
    while True:
        for cnt in range(1, 81):
            print("/" if randint(0,1) == 0 else "\\", end="" if cnt != 80 else "\n")                                 
flag = 0                                  
while True:                
    flag = 1 if flag == 0 else 0           
    print("|",end="")       
    for i in range(0,rooms:=30):
        wall = randint(0,1) 
        if flag == 0:
            print("--+" if wall == 0 else "  +", end="" if i !=29 else "\n")
        else:
            print("  |" if wall == 0  or i == rooms - 1 else "   ", end="" if i!=29 else "\n")
I speak Python but I don't speak English (I just read it a little). If I express myself badly, please blame the translator^^.
Reply
#16
(May-09-2022, 01:11 PM)Coricoco_fr Wrote:
from random import randint        
        for cnt in range(1, 81):
            print("/" if randint(0,1) == 0 else "\\", end="" if cnt != 80 else "\n")                                 

    for i in range(0,rooms:=30):
        wall = randint(0,1) 
        if flag == 0:
            print("--+" if wall == 0 else "  +", end="" if i !=29 else "\n")
        else:
            print("  |" if wall == 0  or i == rooms - 1 else "   ", end="" if i!=29 else "\n")

Wow, those for loops hurt my brain.
Reply
#17
If you remove comments and spacing, got it to 31 lines.
from random import choice, randint
from turtle import Turtle, write, goto, penup, pendown, speed, hideturtle
from time import sleep

# List of 10 colors
colors = ['yellow', 'orange', 'red', 'pink', 'purple', 'blue', 'green', 'brown', 'gray', 'black']

# Hide the turtle and draw the start and finish line
hideturtle(), speed('fastest')
penup(), goto(-200, 10*30/2), pendown(), goto(-200, 0-270)
penup(), goto(200, 10*30/2), pendown(), goto(200, 0-270)

class MyTurtle(Turtle):
    '''Create turtle objects and set properties'''
    def __init__(self, pos):
        super().__init__()
        color = colors.pop(randint(0, len(colors)-1)) if colors else None
        self.color(color), self.shapesize(2)
        self.penup()
        self.goto(-200, (pos*30) - (10*30/2))

# Create a list of turtle objects
turtles = list(MyTurtle(i-2.5) for i in range(1, 11))

# Set a variable for accessing turtle objects
i = 0

# Setup a while loop
racing = True
while racing:
    # Create a random distance to travel and icrease i
    turtles[i := (i + 1) % len(turtles)].forward(randint(0, 5))

    # Track movement of turtle object in list
    # First to line wins goes to home and writes winner
    # Sleep for five seconds to see the winner
    if turtles[i].xcor() >= 200:
        winner = turtles[i]
        winner.write(f'winner: turtle {i+1}', font=('system', 25, 'bold'))
        sleep(5)
        racing = False

Updated code. Now 25 lines without spaces and comments
I welcome all feedback.
The only dumb question, is one that doesn't get asked.

My Scripts
CookBook - Shmup - PyQt5 Music Player


Reply
#18
@menator01 You can remove line 36 if you replace line 37 with
i = (i + 1) % len(turtles)
Reply
#19
(May-09-2022, 06:04 PM)menator01 Wrote: If you remove comments and spacing, got it to 31 lines.
hideturtle(), speed('fastest')
penup(), goto(-200, 10*30/2), pendown(), goto(-200, 0-270)
penup(), goto(200, 10*30/2), pendown(), goto(200, 0-270)

There is another technique that is new to me... can you explain the comma separator between the commands? Does python let you separate commands with a comma the way MS BASIC did with the colon, or is there a special case I am missing?
Reply
#20
Thanks Gribouillis. 30 lines now
I welcome all feedback.
The only dumb question, is one that doesn't get asked.

My Scripts
CookBook - Shmup - PyQt5 Music Player


Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python 100 line Challenge codingCat 9 1,846 Jun-20-2022, 07:18 AM
Last Post: Coricoco_fr
  Zen Python Challenge ichabod801 3 3,506 Aug-13-2018, 12:02 AM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020