猜数字

image.png

  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. import random
  4. """ Number Guessing Game
  5. ----------------------------------------
  6. """
  7. attempts_list = []
  8. def show_score():
  9. if len(attempts_list) <= 0:
  10. print("There is currently no high score, it's yours for the taking!\n")
  11. else:
  12. print("The current high score is {} attempts".format(min(attempts_list)))
  13. def start_game():
  14. print("Hello traveler! Welcome to the game of guesses!\n")
  15. random_number = int(random.randint(1, 10))
  16. player_name = input("What is your name? ")
  17. wanna_play = input("Hi {}, would you like to play the guessing game? (Enter Yes/No) ".format(player_name))
  18. attempts = 0
  19. while wanna_play.lower() == "yes":
  20. if attempts == 0:
  21. show_score()
  22. pass
  23. try:
  24. guess = input("\nPick a number between 1 and 10: ")
  25. if int(guess) < 1 or int(guess) > 10:
  26. raise ValueError("Please guess a number within the given range")
  27. if int(guess) == random_number:
  28. print("Nice! You got it!")
  29. attempts += 1
  30. attempts_list.append(attempts)
  31. print("It took you {} attempts\n".format(attempts))
  32. play_again = input("Would you like to play again? (Enter Yes/No) ")
  33. attempts = 0
  34. #show_score()
  35. random_number = int(random.randint(1, 10))
  36. if play_again.lower() == "no":
  37. print("That's cool, have a good time!")
  38. break
  39. elif int(guess) > random_number:
  40. print("It's lower")
  41. attempts += 1
  42. elif int(guess) < random_number:
  43. print("It's higher")
  44. attempts += 1
  45. except ValueError as err:
  46. print("Oh no!, that is not a valid value. Try again...")
  47. print("({})".format(err))
  48. pass
  49. else:
  50. print("That's cool, have a good time!")
  51. if __name__ == '__main__':
  52. start_game()

石头剪刀布

image.png

  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. import random
  4. import os
  5. import re
  6. """ Rock Paper Scissors
  7. ----------------------------------------
  8. """
  9. while True:
  10. print("\nRock, Paper, Scissors - Shoot!")
  11. userChoice = input("Choose your weapon [R]ock], [P]aper, or [S]cissors: ")
  12. if len(userChoice) < 1 or not re.match("[SsRrPp]", userChoice[0]):
  13. print("Please choose a letter: ")
  14. print("[R]ock, [S]cissors or [P]aper.")
  15. continue
  16. userChoice = userChoice[0].upper()
  17. # Echo the user's choice
  18. print("You chose: " + userChoice)
  19. choices = ['R', 'P', 'S']
  20. opponenetChoice = random.choice(choices)
  21. print("I chose: " + opponenetChoice)
  22. if opponenetChoice == str.upper(userChoice):
  23. print("Tie! ")
  24. elif opponenetChoice == 'R' and userChoice.upper() == 'S':
  25. print("Rock beats scissors, I win! ")
  26. continue
  27. elif opponenetChoice == 'S' and userChoice.upper() == 'P':
  28. print("Scissors beat paper! I win! ")
  29. continue
  30. elif opponenetChoice == 'P' and userChoice.upper() == 'R':
  31. print("Paper beats rock, I win! ")
  32. continue
  33. else:
  34. print("You win!")
  35. pass

网址重定向

  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. import time
  4. from datetime import datetime as dt
  5. """ Website Blocker
  6. ----------------------------------------
  7. """
  8. hosts_path = r"/etc/hosts" # r is for raw string
  9. hosts_temp = "hosts"
  10. redirect = "127.0.0.1"
  11. web_sites_list = ["www.baidu.com", "baidu.com"] # users can modify the list of the websites they want to block
  12. while True:
  13. now = dt.now()
  14. if dt(now.year, now.month, now.day, 9) < now < dt(now.year, now.month, now.day, 12):
  15. print("Working hours")
  16. with open(hosts_path, "r") as file:
  17. content = file.read()
  18. for website in web_sites_list:
  19. if website in content:
  20. pass
  21. else:
  22. content += '\n' + redirect + " " + website
  23. print(content)
  24. #file.write(redirect + " " + website + "\n")
  25. pass
  26. pass
  27. pass
  28. else:
  29. print("Fun time")
  30. with open(hosts_path, "r") as file:
  31. content = file.readlines()
  32. file.seek(0) # reset the pointer to the top of the text file
  33. for line in content:
  34. # here comes the tricky line, basically we overwrite the whole file
  35. if not any(website in line for website in web_sites_list):
  36. print(line)
  37. #file.write(line)
  38. # do nothing otherwise
  39. pass
  40. #file.truncate() # this line is used to delete the trailing lines (that contain DNS)
  41. pass
  42. time.sleep(5)

二分查找

  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. import random
  4. """ Binary Search Algorithm
  5. ----------------------------------------
  6. """
  7. #iterative implementation of binary search in Python
  8. def binary_search(a_list, item):
  9. """
  10. Performs iterative binary search to find the position of an integer in a given, sorted, list.
  11. a_list -- sorted list of integers
  12. item -- integer you are searching for the position of
  13. """
  14. print('the list: ', a_list)
  15. print('the item: ', item)
  16. first = 0
  17. last = len(a_list) - 1
  18. while first <= last:
  19. i = (first + last) // 2
  20. if a_list[i] == item:
  21. return 'found {item} at position {i}'.format(item=item, i=i)
  22. elif a_list[i] > item:
  23. last = i - 1
  24. elif a_list[i] < item:
  25. first = i + 1
  26. else:
  27. return 'not found {item} in the list'.format(item=item)
  28. # recursive implementation of binary search in Python
  29. def binary_search_recursive(a_list, item, idx):
  30. """
  31. Performs recursive binary search of an integer in a given, sorted, list.
  32. a_list -- sorted list of integers
  33. item -- integer you are searching for the position of
  34. """
  35. print('the list: ', a_list)
  36. print('the item: ', item)
  37. print('the idx: ', idx)
  38. print()
  39. first = 0
  40. last = len(a_list) - 1
  41. if len(a_list) == 0:
  42. return '{item} was not found in the list'.format(item=item)
  43. else:
  44. i = (first + last) // 2
  45. if item == a_list[i]:
  46. return '{item} found at {i}'.format(item=item, i=idx+i)
  47. else:
  48. if a_list[i] < item:
  49. return binary_search_recursive(a_list[i+1:], item, idx+i+1)
  50. else:
  51. return binary_search_recursive(a_list[:i], item, idx)
  52. la = [random.randint(1, 30) for i in range(20)]
  53. la.sort()
  54. print(binary_search(la, 28))
  55. print('\n\n---------------------')
  56. print(binary_search_recursive(la, 28, 0))

计算器

image.png

  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. """ Calculator
  4. ----------------------------------------
  5. """
  6. def addition ():
  7. print("\n------------------\nAddition (enter 0 to calculate)")
  8. n = float(input("Enter the number: "))
  9. t = 0 #Total number enter
  10. ans = 0
  11. ipts = []
  12. while n != 0:
  13. ipts.append(n)
  14. ans = ans + n
  15. t += 1
  16. n = float(input("Enter another number: "))
  17. return [ans, ipts]
  18. def subtraction ():
  19. print("\n------------------\nSubtraction (enter 0 to calculate)");
  20. n = float(input("Enter the number: "))
  21. t = 0 #Total number enter
  22. ans = 0
  23. ipts = []
  24. while n != 0:
  25. ipts.append(n)
  26. ans = ans - n
  27. t += 1
  28. n = float(input("Enter another number: "))
  29. return [ans, ipts]
  30. def multiplication ():
  31. print("\n------------------\nMultiplication (enter 0 to calculate)")
  32. n = float(input("Enter the number: "))
  33. t = 0 #Total number enter
  34. ans = 1
  35. ipts = []
  36. while n != 0:
  37. ipts.append(n)
  38. ans = ans * n
  39. t += 1
  40. n = float(input("Enter another number: "))
  41. return [ans, ipts]
  42. def average():
  43. an = addition()
  44. ans = an[0] / len(an[1])
  45. return [ans, an[1]]
  46. # main...
  47. while True:
  48. list = []
  49. print("\n===================\nMy first Python Calculator!")
  50. print("Enter 'a' for addition")
  51. print("Enter 's' for substraction")
  52. print("Enter 'm' for multiplication")
  53. print("Enter 'v' for average")
  54. print("Enter 'q' for quit")
  55. c = input("operation: ")
  56. if c != 'q':
  57. if c == 'a':
  58. list = addition()
  59. print("Ans = ", list[0], "\nthe inputs: ", list[1])
  60. elif c == 's':
  61. list = subtraction()
  62. print("Ans = ", list[0], "\nthe inputs ",list[1])
  63. elif c == 'm':
  64. list = multiplication()
  65. print("Ans = ", list[0], "\nthe inputs ",list[1])
  66. elif c == 'v':
  67. list = average()
  68. print("Ans = ", list[0], "\nthe inputs ",list[1])
  69. else:
  70. print ("Sorry, invilid character")
  71. pass
  72. pass

闹钟

image.png

  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. import datetime
  4. import os
  5. import time
  6. import random
  7. import webbrowser
  8. """ Alarm Clock
  9. ----------------------------------------
  10. """
  11. # If video URL file does not exist, create one
  12. if not os.path.isfile("youtube_alarm_videos.txt"):
  13. print('Creating "youtube_alarm_videos.txt"...')
  14. with open("youtube_alarm_videos.txt", "w") as alarm_file:
  15. alarm_file.write("https://www.youtube.com/watch?v=anM6uIZvx74")
  16. pass
  17. def check_alarm_input(alarm_time):
  18. """Checks to see if the user has entered in a valid alarm time"""
  19. if len(alarm_time) == 1: # [Hour] Format
  20. if alarm_time[0] < 24 and alarm_time[0] >= 0:
  21. return True
  22. elif len(alarm_time) == 2: # [Hour:Minute] Format
  23. if alarm_time[0] < 24 and alarm_time[0] >= 0 and alarm_time[1] < 60 and alarm_time[1] >= 0:
  24. return True
  25. elif len(alarm_time) == 3: # [Hour:Minute:Second] Format
  26. if alarm_time[0] < 24 and alarm_time[0] >= 0 and alarm_time[1] < 60 and alarm_time[1] >= 0 and alarm_time[2] < 60 and alarm_time[2] >= 0:
  27. return True
  28. return False
  29. print('the current time: ', datetime.datetime.now())
  30. # Get user input for the alarm time
  31. print("Set a time for the alarm (Ex. 06:30 or 18:30:00)")
  32. while True:
  33. alarm_input = input(">> ")
  34. try:
  35. alarm_time = [int(n) for n in alarm_input.split(":")]
  36. if check_alarm_input(alarm_time):
  37. break
  38. else:
  39. raise ValueError
  40. except ValueError:
  41. print("ERROR: Enter time in HH:MM or HH:MM:SS format")
  42. pass
  43. # Convert the alarm time from [H:M] or [H:M:S] to seconds
  44. seconds_hms = [3600, 60, 1] # Number of seconds in an Hour, Minute, and Second
  45. alarm_seconds = sum([a*b for a,b in zip(seconds_hms[:len(alarm_time)], alarm_time)])
  46. # Get the current time of day in seconds
  47. now = datetime.datetime.now()
  48. current_time_seconds = sum([a*b for a,b in zip(seconds_hms, [now.hour, now.minute, now.second])])
  49. # Calculate the number of seconds until alarm goes off
  50. time_diff_seconds = alarm_seconds - current_time_seconds
  51. # If time difference is negative, set alarm for next day
  52. if time_diff_seconds < 0:
  53. time_diff_seconds += 86400 # number of seconds in a day
  54. # Display the amount of time until the alarm goes off
  55. #print("Alarm set to go off in %s" % datetime.timedelta(seconds=time_diff_seconds))
  56. # Sleep until the alarm goes off
  57. while time_diff_seconds > 0:
  58. time.sleep(1)
  59. time_diff_seconds -= 1
  60. print("Alarm set to go off in %s" % datetime.timedelta(seconds=time_diff_seconds))
  61. pass
  62. #time.sleep(time_diff_seconds)
  63. # Time for the alarm to go off
  64. print("Wake Up!")
  65. # Load list of possible video URLs
  66. with open("youtube_alarm_videos.txt", "r") as alarm_file:
  67. videos = alarm_file.readlines()
  68. # Open a random video from the list
  69. webbrowser.open(random.choice(videos))

Tic-Tac-Toe

image.png

  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. import random
  4. import sys
  5. """ Tic Tac Toe
  6. ----------------------------------------
  7. """
  8. board = [i for i in range(0, 9)]
  9. player, computer = '',''
  10. # Corners, Center and Others, respectively
  11. moves = ((1,7,3,9), (5,), (2,4,6,8))
  12. # Winner combinations
  13. winners = ((0,1,2), (3,4,5), (6,7,8), (0,3,6), (1,4,7), (2,5,8), (0,4,8), (2,4,6))
  14. # Table
  15. tab = range(1, 10)
  16. def print_board():
  17. x = 1
  18. for i in board:
  19. end = '\n' if x==9 else ' \n---------\n' if x%3==0 else ' | '
  20. char = i if type(i) is str else ' '
  21. x += 1
  22. print(char, end=end)
  23. pass
  24. pass
  25. def select_char():
  26. chars = ('X','O')
  27. if random.randint(0,1) == 0:
  28. return chars[::-1]
  29. return chars
  30. def can_move(brd, player, move):
  31. if move in tab and brd[move-1] == move-1:
  32. return True
  33. return False
  34. def can_win(brd, player, move):
  35. places=[]
  36. x=0
  37. for i in brd:
  38. if i == player:
  39. places.append(x);
  40. x += 1
  41. win = True
  42. for tup in winners:
  43. win = True
  44. for ix in tup:
  45. if brd[ix] != player:
  46. win=False
  47. break
  48. if win == True:
  49. break
  50. return win
  51. def make_move(brd, player, move, undo=False):
  52. if can_move(brd, player, move):
  53. brd[move-1] = player
  54. win = can_win(brd, player, move)
  55. if undo:
  56. brd[move-1] = move-1
  57. return (True, win)
  58. return (False, False)
  59. # AI goes here
  60. def computer_move():
  61. move = -1
  62. # If I can win, others do not matter.
  63. for i in range(1,10):
  64. if make_move(board, computer, i, True)[1]:
  65. move = i
  66. break
  67. if move == -1:
  68. # If player can win, block him.
  69. for i in range(1,10):
  70. if make_move(board, player, i, True)[1]:
  71. move=i
  72. break
  73. if move == -1:
  74. # Otherwise, try to take one of desired places.
  75. for tup in moves:
  76. for mv in tup:
  77. if move == -1 and can_move(board, computer, mv):
  78. move=mv
  79. break
  80. return make_move(board, computer, move)
  81. def space_exist():
  82. return board.count('X') + board.count('O') != 9
  83. player, computer = select_char()
  84. print('Player is [%s] and computer is [%s]' % (player, computer))
  85. result = '\n%%% Deuce ! %%%'
  86. while space_exist():
  87. print_board()
  88. print('\n#Make your move ! [1-9] : ', end='')
  89. move = input()
  90. move = int(move) if move.isdigit() else 0
  91. moved, won = make_move(board, player, move)
  92. if not moved:
  93. print('>> Invalid number ! Try again !')
  94. continue
  95. if won:
  96. result='\n*** Congratulations ! You won ! ***'
  97. break
  98. elif computer_move()[1]:
  99. result='\n=== You lose ! =='
  100. break;
  101. print_board()
  102. print(result)

音乐播放器

image.png

  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. import os
  4. import threading
  5. import time
  6. import tkinter.messagebox
  7. from tkinter import *
  8. from tkinter import filedialog
  9. from tkinter import ttk
  10. from ttkthemes import themed_tk as tk
  11. from mutagen.mp3 import MP3
  12. from pygame import mixer
  13. """ Music Player
  14. ----------------------------------------
  15. """
  16. root = tk.ThemedTk()
  17. root.get_themes() # Returns a list of all themes that can be set
  18. root.set_theme("radiance") # Sets an available theme
  19. # Fonts - Arial (corresponds to Helvetica), Courier New (Courier), Comic Sans MS, Fixedsys,
  20. # MS Sans Serif, MS Serif, Symbol, System, Times New Roman (Times), and Verdana
  21. # Styles - normal, bold, roman, italic, underline, and overstrike.
  22. statusbar = ttk.Label(root, text="Welcome to Melody", relief=SUNKEN, anchor=W, font='Times 10 italic')
  23. statusbar.pack(side=BOTTOM, fill=X)
  24. # Create the menubar
  25. menubar = Menu(root)
  26. root.config(menu=menubar)
  27. # Create the submenu
  28. subMenu = Menu(menubar, tearoff=0)
  29. # playlist - contains the full path + filename
  30. # playlistbox - contains just the filename
  31. # Fullpath + filename is required to play the music inside play_music load function
  32. playlist = []
  33. def browse_file():
  34. global filename_path
  35. filename_path = filedialog.askopenfilename()
  36. add_to_playlist(filename_path)
  37. mixer.music.queue(filename_path)
  38. def add_to_playlist(filename):
  39. filename = os.path.basename(filename)
  40. index = 0
  41. playlistbox.insert(index, filename)
  42. playlist.insert(index, filename_path)
  43. index += 1
  44. menubar.add_cascade(label="File", menu=subMenu)
  45. subMenu.add_command(label="Open", command=browse_file)
  46. subMenu.add_command(label="Exit", command=root.destroy)
  47. def about_us():
  48. tkinter.messagebox.showinfo('About Melody', 'This is a music player build using Python Tkinter')
  49. pass
  50. subMenu = Menu(menubar, tearoff=0)
  51. menubar.add_cascade(label="Help", menu=subMenu)
  52. subMenu.add_command(label="About Us", command=about_us)
  53. mixer.init() # initializing the mixer
  54. root.title("Melody")
  55. root.iconbitmap(r'images/melody.ico')
  56. # Root Window - StatusBar, LeftFrame, RightFrame
  57. # LeftFrame - The listbox (playlist)
  58. # RightFrame - TopFrame,MiddleFrame and the BottomFrame
  59. leftframe = Frame(root)
  60. leftframe.pack(side=LEFT, padx=30, pady=30)
  61. playlistbox = Listbox(leftframe)
  62. playlistbox.pack()
  63. addBtn = ttk.Button(leftframe, text="+ Add", command=browse_file)
  64. addBtn.pack(side=LEFT)
  65. def del_song():
  66. selected_song = playlistbox.curselection()
  67. selected_song = int(selected_song[0])
  68. playlistbox.delete(selected_song)
  69. playlist.pop(selected_song)
  70. pass
  71. delBtn = ttk.Button(leftframe, text="- Del", command=del_song)
  72. delBtn.pack(side=LEFT)
  73. rightframe = Frame(root)
  74. rightframe.pack(pady=30)
  75. topframe = Frame(rightframe)
  76. topframe.pack()
  77. lengthlabel = ttk.Label(topframe, text='Total Length : --:--')
  78. lengthlabel.pack(pady=5)
  79. currenttimelabel = ttk.Label(topframe, text='Current Time : --:--', relief=GROOVE)
  80. currenttimelabel.pack()
  81. def show_details(play_song):
  82. file_data = os.path.splitext(play_song)
  83. if file_data[1] == '.mp3':
  84. audio = MP3(play_song)
  85. total_length = audio.info.length
  86. else:
  87. a = mixer.Sound(play_song)
  88. total_length = a.get_length()
  89. # div - total_length/60, mod - total_length % 60
  90. mins, secs = divmod(total_length, 60)
  91. mins = round(mins)
  92. secs = round(secs)
  93. timeformat = '{:02d}:{:02d}'.format(mins, secs)
  94. lengthlabel['text'] = "Total Length" + ' - ' + timeformat
  95. t1 = threading.Thread(target=start_count, args=(total_length,))
  96. t1.start()
  97. def start_count(t):
  98. global paused
  99. # mixer.music.get_busy(): - Returns False when we press the stop button (music stop playing)
  100. # Continue - Ignores all of the statements below it. We check if music is paused or not.
  101. current_time = 0
  102. while current_time <= t and mixer.music.get_busy():
  103. if paused:
  104. continue
  105. else:
  106. mins, secs = divmod(current_time, 60)
  107. mins = round(mins)
  108. secs = round(secs)
  109. timeformat = '{:02d}:{:02d}'.format(mins, secs)
  110. currenttimelabel['text'] = "Current Time" + ' - ' + timeformat
  111. time.sleep(1)
  112. current_time += 1
  113. pass
  114. pass
  115. def play_music():
  116. global paused
  117. if paused:
  118. mixer.music.unpause()
  119. statusbar['text'] = "Music Resumed"
  120. paused = False
  121. else:
  122. try:
  123. stop_music()
  124. time.sleep(1)
  125. selected_song = playlistbox.curselection()
  126. selected_song = int(selected_song[0])
  127. play_it = playlist[selected_song]
  128. mixer.music.load(play_it)
  129. mixer.music.play()
  130. statusbar['text'] = "Playing music" + ' - ' + os.path.basename(play_it)
  131. show_details(play_it)
  132. except:
  133. tkinter.messagebox.showerror('File not found', 'Melody could not find the file. Please check again.')
  134. pass
  135. def stop_music():
  136. mixer.music.stop()
  137. statusbar['text'] = "Music Stopped"
  138. paused = False
  139. def pause_music():
  140. global paused
  141. paused = True
  142. mixer.music.pause()
  143. statusbar['text'] = "Music Paused"
  144. def rewind_music():
  145. play_music()
  146. statusbar['text'] = "Music Rewinded"
  147. def set_vol(val):
  148. volume = float(val) / 100
  149. mixer.music.set_volume(volume)
  150. # set_volume of mixer takes value only from 0 to 1. Example - 0, 0.1,0.55,0.54.0.99,1
  151. muted = False
  152. def mute_music():
  153. global muted
  154. if muted: # Unmute the music
  155. mixer.music.set_volume(0.7)
  156. volumeBtn.configure(image=volumePhoto)
  157. scale.set(70)
  158. muted = False
  159. else: # mute the music
  160. mixer.music.set_volume(0)
  161. volumeBtn.configure(image=mutePhoto)
  162. scale.set(0)
  163. muted = True
  164. pass
  165. middleframe = Frame(rightframe)
  166. middleframe.pack(pady=30, padx=30)
  167. playPhoto = PhotoImage(file='images/play.png')
  168. playBtn = ttk.Button(middleframe, image=playPhoto, command=play_music)
  169. playBtn.grid(row=0, column=0, padx=10)
  170. stopPhoto = PhotoImage(file='images/stop.png')
  171. stopBtn = ttk.Button(middleframe, image=stopPhoto, command=stop_music)
  172. stopBtn.grid(row=0, column=1, padx=10)
  173. pausePhoto = PhotoImage(file='images/pause.png')
  174. pauseBtn = ttk.Button(middleframe, image=pausePhoto, command=pause_music)
  175. pauseBtn.grid(row=0, column=2, padx=10)
  176. # Bottom Frame for volume, rewind, mute etc.
  177. bottomframe = Frame(rightframe)
  178. bottomframe.pack()
  179. rewindPhoto = PhotoImage(file='images/rewind.png')
  180. rewindBtn = ttk.Button(bottomframe, image=rewindPhoto, command=rewind_music)
  181. rewindBtn.grid(row=0, column=0)
  182. mutePhoto = PhotoImage(file='images/mute.png')
  183. volumePhoto = PhotoImage(file='images/volume.png')
  184. volumeBtn = ttk.Button(bottomframe, image=volumePhoto, command=mute_music)
  185. volumeBtn.grid(row=0, column=1)
  186. scale = ttk.Scale(bottomframe, from_=0, to=100, orient=HORIZONTAL, command=set_vol)
  187. scale.set(70) # implement the default value of scale when music player starts
  188. mixer.music.set_volume(0.7)
  189. scale.grid(row=0, column=2, pady=15, padx=30)
  190. def on_closing():
  191. stop_music()
  192. root.destroy()
  193. pass
  194. root.protocol("WM_DELETE_WINDOW", on_closing)
  195. root.mainloop()

assets.zip