r/inventwithpython • • Jul 01 '20

Multiclipboard project from Automate is not working

2 Upvotes
#! python 3
# mcb.pyw - Saves and loads pieces of text to the clipboard.
# Usage: py.exe mcb.pyw save <keyword> - Saves clipboard to keyword.
#        py.exe mcb.pyw <keyword> - Loads keyword to clipboard.
#        py.exe mcb.pyw list - Loads all keywords to clipboard.

import shelve
import pyperclip
import sys

mcbShelf = shelve.open('mcb')

# Save clipboard content.
if len(sys.argv) == 3 and sys.argv[1].lower() == 'save':
    mcbShelf[sys.argv[2]] = pyperclip.paste()
elif len(sys.argv) == 2:
    # List keywords and load content.
    if sys.argv[1].lower() == 'list':
        pyperclip.copy(str(list(mcbShelf.keys())))
    elif sys.argv[1] in mcbShelf:
        pyperclip.copy(mcbShelf[sys.argv[1]])

mcbShelf.close()

I've tried running it both by 'py.exe mcb.pyw save <keyword>' and 'mcb.pyw save <keyword>' but when I try to list it, the keyword does not get saved to clipboard.

The same thing happens for the second command, I tried checking if it works by copying text then saving it, copying some other text and then trying to get the previously copied text using the keyword. This is not working either


r/inventwithpython • • Jun 12 '20

Importing openpyxl

2 Upvotes

I'm a complete beginner, working through "Automate the Boring Stuff with Python"

I'm trying to import openpyxl but this leads to the error "ModuleNotFoundError: No module named 'openpyxl'"

I've installed openpyxl with pip, and when I try to reinstall it comes up with the following:

"Requirement already satisfied: openpyxl==2.6.2 in c:\users\jonny\pycharmprojects\giraffe\venv\lib\site-packages (2.6.2)Requirement already satisfied: jdcal in c:\users\jonny\pycharmprojects\giraffe\venv\lib\site-packages (from openpyxl==2.6.2) (1.4.1)Requirement already satisfied: et_xmlfile in c:\users\jonny\pycharmprojects\giraffe\venv\lib\site-packages (from openpyxl==2.6.2) (1.0.1)"

This sounds to me like it's already installed so I don't know why it doesn't seem to be working. Any help would be massively appreciated!


r/inventwithpython • • May 28 '20

Invent Games:Dragon Realm - Cannot loop around to replay the game

2 Upvotes

The game seems to work pefectly the first time through but when prompted to play again, even if I enter 'yes' I get dropped back to the python prompt instead of seeing the intro text.

Here's the output: https://pastebin.com/Twfua7rM

and here's my code: https://pastebin.com/G94T8uLq

I've copied a friend's working version of the program but I get the same problem with his working code on my machine.

So this seems to be specific to my python version or setup, any ideas what this might be?


r/inventwithpython • • Apr 10 '20

mclip - can't find file or directory

2 Upvotes

Can't seem to run the bat file succesfully. It does seem to run but gets hung up and doesn't find the target script file? I get the same result when I run the bat file using the Win-R window. It doesn't seem to me that this should be happening since I am clearly using absolute paths. What am I not undrestanding.

Directory of C:\Users\KentSurface\PycharmProjects\Automate the Boring Stuff

04/03/2020 08:38 PM 780 IsChessBoard.py

04/08/2020 04:29 PM 94 mclip.bat

04/08/2020 10:10 AM 676 mclip.py

When I run the bat file from the same directory that the script file is in I get:

(Automate the Boring Stuff) C:\Users\KentSurface\PycharmProjects\Automate the Boring Stuff>mclip.bat

C:\Users\KentSurface\AppData\Local\Programs\Python\Python38-32\python.exe: can't open file 'C:\Users\KentSurface\PycharmProjects\Automate': [Errno 2] No such file or directory

Press any key to continue . . .

mclip.bat: (for some reason when I paste the @ sign is replaced by u/)

u/py.exe C:\Users\KentSurface\PycharmProjects\Automate the Boring Stuff\mclip.py %*

u/pause


r/inventwithpython • • Apr 07 '20

pyinputplus and pyperclip module not found

2 Upvotes

Apparently neither of these modules work with Python 3.8. I am using PyCharm and Py 3.8 on a Win 10 machine. Is there a reasonable workaround or do I need to regress my software to some other version. I previously found, when working my way through Python Crash Course that one of the modules referenced in that book required 3.7.1 or higher so installed 3.8 and found new problems. Is there something specific to Python that it has forward and backward compatibility issues? If I can't get these two modules to work does it make sense to just forge ahead to some of the chapters that don't use them or am I just going to find more of these problems. Really don't want to have to configure my system every time I find a problem. Or maybe there is something fundamental that I don't understand?


r/inventwithpython • • Feb 20 '20

Issues with pyautogui.drag

2 Upvotes

Hey All,

I am almost done Automate the Boring Stuff and I have run into a standstill on the last chapter with PyAutoGui module. I have been using Spyder on MacOS Catalina. On Spyder I could not get pyautogui to work at all so I migrated to Sublime text and the example of moving the cursor in a square finally worked. Now when I try to do the drawing example I get the first initial click to work then the dragging part does not work as after about 5-10 seconds I get an error saying that the button argument is not in ('left', 'middle', 'right')

What Ive done so far:

pip3 install pyobjc-core & pip3 install pyobjc

Changed the accessibility of the program (I couldn't get Spyder as an application since it runs off Anaconda but I added Anaconda... I'm assuming this is why Spyder won't work for me)

Used Sublime Text and gave it permission to control my computer so the cursor moving in a squares works. Dragging however does not work as seen in the error below.

Downloaded Mu - but then couldn't even figure out how to import a module as they all go unfound. Saw on a site that you can click on the gear in the bottom right corner to add other modules. I clicked on the gear but saw no tab about adding 3rd party modules.

import pyautogui
import time

time.sleep(5)
pyautogui.click()
distance = 300
change = 20
while distance > 0:
    pyautogui.drag(distance, 0, duration=0.5)  # move right
    distance -= 5
    pyautogui.drag(0, distance, duration=0.5)  # move down
    pyautogui.drag(-distance, 0, duration=0.5)  # move left
    distance -= 5
    pyautogui.drag(0, -distance, duration=0.5)  # move up
    
Traceback (most recent call last):

  File "<ipython-input-17-64e4044b435e>", line 9, in <module>
    pyautogui.drag(distance, 0, duration=0.5)  # move right

  File "/Users/username/.local/lib/python3.7/site-packages/pyautogui/__init__.py", line 964, in dragRel
    _mouseMoveDrag('drag', mousex, mousey, xOffset, yOffset, duration, tween, button)

  File "/Users/username/.local/lib/python3.7/site-packages/pyautogui/__init__.py", line 1073, in _mouseMoveDrag
    platformModule._dragTo(tweenX, tweenY, button)

File "/Users/username/.local/lib/python3.7/site-packages/pyautogui/_pyautogui_osx.py", line 436, in _dragTo

    assert False, "button argument not in ('left', 'middle', 'right')"

AssertionError: button argument not in ('left', 'middle', 'right')

Any help would be greatly appreciated!


r/inventwithpython • • Jan 13 '20

ModuleNotFoundError in Mu editor

2 Upvotes

Hello,

Im trying to use the "paramiko" package in my code in Mu editor and it throws me an error:

In[1]: import paramiko

---------------------------------------------------------------------------

ModuleNotFoundError Traceback (most recent call last)

<ipython-input-3-110cb50357c7> in <module>

----> 1 import paramiko

ModuleNotFoundError: No module named 'paramiko'

In[2]:

But, the package has been successfully installed and works on the CMD

C:\Users\username>pip3 install paramiko

Requirement already satisfied: paramiko in c:\users\username\appdata\local\programs\python\python38\lib\site-packages (2.7.1)

Requirement already satisfied: cryptography>=2.5 in c:\users\username\appdata\local\programs\python\python38\lib\site-packages (from paramiko) (2.8)

Requirement already satisfied: pynacl>=1.0.1 in c:\users\username\appdata\local\programs\python\python38\lib\site-packages (from paramiko) (1.3.0)

Requirement already satisfied: bcrypt>=3.1.3 in c:\users\username\appdata\local\programs\python\python38\lib\site-packages (from paramiko) (3.1.7)

Requirement already satisfied: six>=1.4.1 in c:\users\username\appdata\local\programs\python\python38\lib\site-packages (from cryptography>=2.5->paramiko) (1.13.0)

Requirement already satisfied: cffi!=1.11.3,>=1.8 in c:\users\username\appdata\local\programs\python\python38\lib\site-packages (from cryptography>=2.5->paramiko) (1.13.2)

Requirement already satisfied: pycparser in c:\users\username\appdata\local\programs\python\python38\lib\site-packages (from cffi!=1.11.3,>=1.8->cryptography>=2.5->paramiko) (2.19)

WARNING: You are using pip version 19.2.3, however version 19.3.1 is available.

You should consider upgrading via the 'python -m pip install --upgrade pip' command.

C:\Users\username>cd /

C:\>cd C:\Users\username\AppData\Local\Programs\Python\Python38

C:\Users\username\AppData\Local\Programs\Python\Python38>python

Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)] on win32

Type "help", "copyright", "credits" or "license" for more information.

>>> import paramiko

>>>

Any inputs are really appreciated


r/inventwithpython • • Nov 24 '19

Can't import Selenium in the MuEditor

2 Upvotes

Hi everyone,

In Chapter 12, I can't import Selenium in the Mu editior, how did you do it? The appendix A says how to do it in UI, but there's no UI for that in my Mu Editor. I tried to do it via the command line, no success. I don't understand the instructions:

"For example, after you download the requirements file for your operating system from https://nostarch.com/automatestuff2/, run the following: " Where is that file?

" On Windows:

pip install –r automate-win-requirements.txt --target "C:\Users\USERNAME
\AppData\Local\Mu\pkgs"

"If you want to install only some of the modules, you can run the regular pip (or pip3) command and add the --target argument. " Why am I told to add the --target argument? It's already there, is it supposed to be written twice?

I tried writing "pip install --user selenium==3.141.0 --target "C:\Users\<me>\AppData\Local\Mu\pkgs" but I got an error:

Collecting selenium==3.141.0

Using cached https://files.pythonhosted.org/packages/80/d6/4294f0b4bce4de0abf13e17190289f9d0613b0a44e5dd6a7f5ca98459853/selenium-3.141.0-py2.py3-none-any.whl

Collecting urllib3 (from selenium==3.141.0)

Using cached https://files.pythonhosted.org/packages/b4/40/a9837291310ee1ccc242ceb6ebfd9eb21539649f193a7c8c86ba15b98539/urllib3-1.25.7-py2.py3-none-any.whl

Installing collected packages: urllib3, selenium

ERROR: Exception:

Traceback (most recent call last):

File "c:\users\<me>\appdata\local\programs\python\python38\lib\site-packages\pip_internal\cli\base_command.py", line 188, in main

status = self.run(options, args)

File "c:\users\<me>\appdata\local\programs\python\python38\lib\site-packages\pip_internal\commands\install.py", line 398, in run

installed = install_given_reqs(

File "c:\users\<me>\appdata\local\programs\python\python38\lib\site-packages\pip_internal\req__init__.py", line 54, in install_given_reqs

requirement.install(

File "c:\users\<me>\appdata\local\programs\python\python38\lib\site-packages\pip_internal\req\req_install.py", line 925, in install

self.move_wheel_files(

File "c:\users\<me>\appdata\local\programs\python\python38\lib\site-packages\pip_internal\req\req_install.py", line 453, in move_wheel_files

wheel.move_wheel_files(

File "c:\users\<me>\appdata\local\programs\python\python38\lib\site-packages\pip_internal\wheel.py", line 324, in move_wheel_files

scheme = distutils_scheme(

File "c:\users\<me>\appdata\local\programs\python\python38\lib\site-packages\pip_internal\locations.py", line 111, in distutils_scheme

i.finalize_options()

File "c:\users\<me>\appdata\local\programs\python\python38\lib\distutils\command\install.py", line 252, in finalize_options

raise DistutilsOptionError("can't combine user with prefix, "

distutils.errors.DistutilsOptionError: can't combine user with prefix, exec_prefix/home, or install_(plat)base

WARNING: You are using pip version 19.2.3, however version 19.3.1 is available.

You should consider upgrading via the 'python -m pip install --upgrade pip' command.

I also noticed that if I run a program such as:

from selenium import webdriver

browser = webdriver.Firefox()

type(browser)

browser.get('https://inventwithpython.com')

test = input()

It doesn't reach the 5th line and closes before. Is it related?

Thank you for your help!


r/inventwithpython • • Nov 22 '19

Cannont run the run the Multiclipboard program at the end of Chapter 8 in the Automate the Boring Stuff With Python book

2 Upvotes

Hello all,

I have some troubles to run the Multiclipboard at the end of Chapter 8 in the Automate the Boring Stuff With Python book.

I tried to run it like the Password Locker project in Chapter 6 with: pressing Win-R and typing mcb save <some keyword> and mcb <some keyword> to retrieve the value stored in the shelf file.

My mcb.bat file looks like this:

@pyw.exe C:\MyPythonScripts\mcb.pyw %*

@pause

And the mcb.pyw file is the one I downloaded from the additional content page on https://automatetheboringstuff.com/

Anyone could explain how to run this program?

Thank you all.


r/inventwithpython • • Nov 07 '19

how to convert an if-else statement to a linear programming constraint in Python

2 Upvotes

I have two variables E[i] and Y[i], where E is a continuous variable and Y is binary.So the condition is:

if E[i] <= rmin:
    Y[i]==1
else:
    Y[i]==0

How do I convert this if-else loop to linear constraint using Python.


r/inventwithpython • • Oct 18 '19

Link to download beeps.wav broken

2 Upvotes

The link in Making Games with Python & Pygame to download the beeps.wav is broken. Where do I get the downloads for this book?

Thank you.


r/inventwithpython • • Jun 18 '19

Creating a Chatbot with RiveScript - p.1 Introduction

Thumbnail
youtube.com
2 Upvotes

r/inventwithpython • • Apr 17 '19

Correction to 'Cracking Codes with Python'

2 Upvotes

Al,

I'm enjoying 'Cracking Codes with Python', and find your approach of teaching a language by working through a specific subject to be very useful. I'm reading Chapter 5, 'The Caesar Cipher', and noticed the section 'The in and not in Operators' on page 62 contains the statement, "Also, a blank string is always considered to be in any other string."

This should read, "Also, a null string is always considered to be in any other string."

For example,

Blank String: >>> " " in "helloworld"

False

Null String: >>> "" in "helloworld"

True

The associated example in the book does correctly show a null string.


r/inventwithpython • • Apr 13 '19

Chapter2 catanim.py script = black pygame window --- works with my code --- WHY?

2 Upvotes

I copied code from https://inventwithpython.com/catanimation.py

When I run the code from IDLE 3.7.2 - the pygame window is black.

I replaced code on line 10:

DISPLAYSURF = pygame.display.set_mode((400, 300), 0, 32)

with:

size = [400, 300]

screen = pygame.display.set_mode(size)

I replaced code on line 20:

DISPLAYSURF.fill(WHITE)

with:

screen.fill(WHITE)

I replaced code on line 39:

with:

screen.blit(catImg, (catx, caty))

When I run the code now, the window background is white and cat repeats a circuit around the window perimeter.

My question is why doesn't the original code work?

I spent a fair bit of time searching the net for answers and looked on this forum to see if anyone else had the same problem, but I could find no answers.

I am somewhat discouraged to think that I will have to substitute code to work my way through the rest of the book, without understanding why the original code does not work for me.

If anyone can offer an explanation, I would appreciate the help.

#############################################

ADDENDUM

Now when I run the original code, it works fine. It did not work until after I did the code substitution and that window behaved correctly. I tried the original code around 30 times before I tried the code substitution.

I guess my question now is WTF?

Has anyone else had this problem?


r/inventwithpython • • Apr 11 '19

tic-tac-toe PlayerVersusPlayer python code.

2 Upvotes

Hi, I am working on a raspberry pi school project, and I wanted to make a simple game.

While doing research I stumbled upon your site with the code for the game and the explanation for each of the lines.

When I copied the code and pasted it in Thonny, everything worked, I also translated the words to norwegian as the teacher demanded us to (i`m in a norwegian school btw).

And since our teacher is lazy and doesn`t really care if you copied the project from the internet or made it yourself, having a code like this would make it insanely easy to get a straight A.

But I found it quite boring to be honest, so I decided to remake the code to be PVP, instead of PlayerVersusComputer.

The problem is, I dont know how. I thought it would be as simple as replacing the "def getComputerMove"-line with "def getPlayerMove" and renaming all "Player" codes to "Player1" and "Computer" to "Player2"

I tried running the game, and everything was fine, except for the fact that Player 2, instead of getting the opposite letter, gets the same one as Player 1, and also, the board only shows when it is player 1`s turn.

So it is basically tic-tac-toe with Player 1 playing with himself on a 3x3 board.

I think I have tried everything and I just can`t find the answer, I troubleshooted, googled it, and asked my classmates if they have any solutions (as if that would help, they are the "copy-paste and Ace the presentation" type of guys)

I will continue troubleshooting and will comment this post that I solved the issue and everythings fine.

But if you have any suggestions on how to solve this problem, it would help me a lot. Thank you for reading :)


r/inventwithpython • • Mar 30 '19

Facebook Login Automation in 11 lines of code | Python 3.6

Thumbnail
youtube.com
2 Upvotes

r/inventwithpython • • Feb 11 '19

ATBS Chapter 16 - reading emails.

2 Upvotes

https://automatetheboringstuff.com/chapter16/

In your example on how to read mails from a imap server you wrote following code:

 message = pyzmail.PyzMessage.factory(rawMessages[40041]['BODY[]']) 

But this gives a key error. I checked the content of rawMessages and to get the body of the mail you have to use [b'BODY[]']

 message = pyzmail.PyzMessage.factory(rawMessages[40041][b'BODY[]']) 

I guess if r'string' is a raw string the b'string' is a binary one? Can't remember that this stringmode was introduced in atbs.

Greetings


r/inventwithpython • • Feb 10 '19

ATBS Chapter 14 json-API

2 Upvotes

Hello.

First. Very nice Book. I love it and it's very well written to get into programming.

But please think about changing the example with openweathermap so that at least it is pointed out that a registration is necessary to use the api in the meantime.

Or even better: Rewrite the example to the freely accessible Wikipedia-api where no api-keys are needed (see code in comment). One reason for this is that the module requests was not explained well enough to handle ssl requests and I guess sending the api-key in plain text is rather suboptimal?

Greetings Apop

One more thing. In the questions for chapter 14 you ask:

Q:3. What modes do File objects for reader and Writer objects need to be opened in?

And you answer this with:

3. File objects need to be opened in read-binary ('rb') for Reader objects and write-binary ('wb') for Writer objects.

But... why? As you explained csv is pure text data and no binary so no need to read or write in binary and you also never used 'rb' or 'wb' in your examples in chapter 14


r/inventwithpython • • Jan 22 '19

Freshly Installed IDLE Shuts Down With Subprocess Error At Startup (Linux; Ubuntu; KDE Neon)

2 Upvotes

I have just started working through "Automate the Boring Stuff", and I have installed IDLE3 via "sudo apt-get install idle3", and python3-pip via "sudo apt-get install python3-pip" on my Linux machine (KDE Neon, based on Ubuntu). But I cannot seem to get IDLE to work.

When I run IDLE, I am greeted with the following error:

"IDLE's subprocess didn't make connection. Either IDLE can't start a subprocess or personal firewall software is blocking the connection."

After I click "OK", IDLE shuts down.

I have tried figuring out how to troubleshoot this error, but it seems I keep getting three recommendations:

(1) Delete all .py and pyc files in a specific directory (?) ← this seems to be coming from Mac and Win users

(2) Move Python to a different place ← Win users?

(3) Shut down all running python processes ← none running (= none shown in htop)

I have tried to make sense of the first two approaches in KDE, but I cannot seem to find any python programs to delete (not sure where and how to look), and I would also not know where and how to move Python.

Since I now seem to have two instances (?) or versions (?) of IDLE installed—I get both "IDLE" and "IDLE (using Python-3.5)" in my applications menu—, I am assuming it might have something to do with that.

Was tempted to remove idle3, but not sure about the associated packages (blt idle-python3.5 python3-tk tk8.6-blt2.5), so I did not remove anything lest I mess up my system.

Same with python3-pip, which not only introduced new packages (libexpat1-dev libpython3-dev libpython3.5-dev python-pip-whl python3-dev python3-pip python3-setuptools python3-wheel python3.5-dev), but also upgraded some (libpython3.5 libpython3.5-minimal libpython3.5-stdlib python3.5 python3.5-minimal).

I am running KDE Neon LTS 5.12.

I am sorry if this is the wrong place to ask, but any help, any pointers as to how to troubleshoot this issue would be greatly appreciated.


r/inventwithpython • • Jan 12 '19

Coding for noobs

2 Upvotes

Is there a specific reddit for people who want to learn how to code?


r/inventwithpython • • Dec 14 '18

AtBS: Google Sheets

2 Upvotes

Hey /u/AlSweigart

Any chance of some additional content (addendum, blog post, something) related to using Python with Google Sheets, much like the chapter on Excel?

I know there are various other articles or tutorials already, but none with quite your focused problem solving approach!

Thanks!


r/inventwithpython • • Dec 07 '18

Python. Why error? Help me please.

2 Upvotes
  1. import re

  2. phoneRegex = re.compile(r"""

  3. \+\d{1,2}(\s\-)?

  4. \(\d{3}\)(\-)?

  5. \d{3}(\-)?

  6. \d{2}(\-)?

  7. \d{2}

  8. """, re.VERBOSE)

  9. mo = phoneRegex.findall('My number is: +38(050)-453-25-12 +7(495) 162-24-30.')

  10. print('Found number is: ' + mo)

File "C:/Users//untitled1/Test.py", line 11, in <module>

print('Found number is: ' + mo)

TypeError: must be str, not list


r/inventwithpython • • Nov 27 '18

When I fail 6 times it just goes blank?

2 Upvotes

import random
guessesTaken = 0
print('Hello! What is your name?')
myName = input()
number = random.randint(1, 20)
print('Well, ' + myName + ', I am thinking of a number between 1 and 20.')
for guessesTaken in range(6):
print('Take a guess.')
guess = input()
guess = int(guess)
if guess < number:
print('Your guess is too low')

if guess > number:
print('Your guess is too high.')

if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken+1)
print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number + '.')

When I fail it just goes blank?


r/inventwithpython • • Nov 15 '18

pylint errors that make no sense?

2 Upvotes

I'm new to Python and every time I try running Pygame i get these errors:

Module 'pygame' has no 'quit' member

Module 'pygame' has no 'QUIT' member

Module 'pygame' has no 'KEYDOWN' member

Module 'pygame' has no 'K_RIGHT' member

Module 'pygame' has no 'K_UP' member

Module 'pygame' has no 'K_DOWN' member

Module 'pygame' has no 'K_LEFT' member

How can I fix this??????


r/inventwithpython • • Oct 19 '18

Stuck trying to understand explanation for block of code

2 Upvotes

Hi,

In chapter 13 of the book "Invent your Own Computer Games with Python" I am stuck trying to understand the explanation for a block of code. See link: https://inventwithpython.com/invent4thed/chapter13.html

The explanation for lines 183 - 189 of the code (under the subtitle "Finding a Sunken Treasure Chest", towards the bottom of the webpage linked above), is: "If makeMove() doesn’t return False, it returns a string of the results of that move. If this string is 'You have found a sunken treasure chest!', then all the sonar devices on the board should update to detect the next closest treasure chest on the board..."

else:

if moveResult == 'You have found a sunken treasure chest!':

# Update all the sonar devices currently on the map.

for x, y in previousMoves:

makeMove(theBoard, theChests, x, y)

drawBoard(theBoard)

print(moveResult)

(because the above code is pasted without the rest of the script, it is not indented in line with the rest of the script obviously)

BUT, surely the only sonar which is coded to detect the treasure chests is the one the player placed during their current move? So why does the whole makeMove function need to be called again just to update the distance between each previously placed sonar and the treasure chests that remain after the player correctly found one of them?

Here is the function that runs once the player makes their move that calculates and outputs the distance between the player's placed sonar and the closest treasure chest on the board:

def makeMove(board, chests, x, y):

# Change the board data structure with a sonar device character. Remove treasure chests from the chests list as they are found.

# Return False if this is an invalid move.

# Otherwise, return this string of the result of this move.

smallestDistance = 100 # Any chest will be closer than 100.

for cx, cy in chests:

distance = math.sqrt((cx - x) * (cx - x) + (cy - y) * (cy - y))

if distance < smallestDistance: # We want the closest treasure chest.

smallestDistance = distance

smallestDistance = round(smallestDistance)

if smallestDistance == 0:

# xy is directly on a treasure chest!

chests.remove([x, y])

return 'You have found a sunken treasure chest!'

else:

if smallestDistance < 10:

board[x][y] = str(smallestDistance)

return 'Treasure detected at a distance of %s from the sonar device.' % (smallestDistance)

else:

board[x][y] = 'X'

return 'Sonar did not detect anything. All treasure chests out of range.'