I am trying to be able to have a person specify how many sets of dice they want to roll. at present if they want to roll three sets of a d100 they have to enter the command 3 times. I want to be able to have them enter an amount like !3d100 and have it roll it 3 times?
#client.command(name='d100', help='Rolls a d100 sice')
async def dice(context):
diceEmbed = discord.Embed(title="Rolling for " + str(context.message.author.display_name), color=0xCC5500)
roll = (random.randint(1, 100))
url = "http://157.230.225.61/images/dice/d100/d100_{:03}.png"
url = url.format(roll)
diceEmbed.set_image(url=url)
diceEmbed.add_field(name="d100", value=roll, inline=True)
if roll == 1:
diceEmbed.set_footer(text="FUMBLE")
await context.message.channel.send(embed=diceEmbed)
First of all consider using f string. You will have to add a input to your command !dice 3 This will give you 3 rolls if no amount given only 1.
Keep in mind in embed you can only place one image so i took the highest according to you.
#bot.command()
async def dice(ctx, amount: int = 1):
diceEmbed = discord.Embed(title=f"Rolling for {ctx.message.author.display_name}", color=0xCC5500)
max_roll = 0
for i in range(amount):
roll = (random.randint(1, 100))
if roll > max_roll:
url = f"http://157.230.225.61/images/dice/d100/d100_{roll:03d}.png"
max_roll = roll
diceEmbed.add_field(
name=f"Role number {i+1}", value=roll, inline=False)
if roll == 1:
diceEmbed.set_footer(text="FUMBLE")
# You can have only one image which is the highest
diceEmbed.set_image(url=url)
await ctx.message.channel.send(embed=diceEmbed)
Related
I have a bot in writing in python and I want to incorporate a number game into the bot. The game code is below. (nl is a variable to say os.linesep)
secret_number = random.randint(0, 100)
guess_count = 0
guess_limit = 5
print(f'Welcome to the number guessing game! The range is 0 - 100 and you have 5 attempts to guess the correct number.')
while guess_count < guess_limit:
guess = int(input('Guess: '))
guess_count += 1
if guess > secret_number:
print('Too High.', nl, f"You have {guess_limit - guess_count} attempts remaining.")
elif guess < secret_number:
print('Too Low.', nl, f"You have {guess_limit - guess_count} attempts remaining.")
elif guess == secret_number:
print("That's correct, you won.")
break
else:
print("Sorry, you failed.")
print(f'The correct number was {secret_number}.')
So I want to be able to use that in the discord messaging system. My issue is that I need the bot to scan the most recent messages for a number from that specific user that initiated the game. How could I do so?
To simplify my question how can I say this:
if message from same message.author = int():
guess = that^
The solution here would be to wait_for another message from that user. You can do this with:
msg = await client.wait_for('message', check=message.author == PREVIOUS_SAVED_MSG_AUTHOR_AS_VARIABLE, timeout=TIMEOUT)
# You don't really need a timeout but you can add one if you want
# (then you'd need a except asyncio.TimeoutError)
if msg.content == int():
guess = msg
else:
...
I've created a program for a project that tests images against one another to see whether or not it's the same image or not. I've decided to use correlation since the images I am using are styled in the same way and with this, I've been able to get everything working up to this point.
I now wish to create an array of images again, but this time, in order of their correlation. So for example, if I'm testing a 50 pence coin and I test 50 images against the 50 pence coin, I want the highest 5 correlations to be stored into an array, which can then be used for later use. But I'm unsure how to do this as each item in the array will need to have more than one variable, which will be the image location/name of the image and it's correlation percentage.
%Program Created By Ben Parry, 2016.
clc(); %Simply clears the console window
%Targets the image the user picks
inputImage = imgetfile();
%Targets all the images inside this directory
referenceFolder = 'M:\Project\MatLab\Coin Image Processing\Saved_Images';
if ~isdir(referenceFolder)
errorMessage = print('Error: Folder does not exist!');
uiwait(warndlg(errorMessage)); %Displays an error if the folder doesn't exist
return;
end
filePattern = fullfile(referenceFolder, '*.jpg');
jpgFiles = dir(filePattern);
for i = 1:length(jpgFiles)
baseFileName = jpgFiles(i).name;
fullFileName = fullfile(referenceFolder, baseFileName);
fprintf(1, 'Reading %s\n', fullFileName);
imageArray = imread(fullFileName);
imshow(imageArray);
firstImage = imread(inputImage); %Reading the image
%Converting the images to Black & White
firstImageBW = im2bw(firstImage);
secondImageBW = im2bw(imageArray);
%Finding the correlation, then coverting it into a percentage
c = corr2(firstImageBW, secondImageBW);
corrValue = sprintf('%.0f%%',100*c);
%Custom messaging for the possible outcomes
corrMatch = sprintf('The images are the same (%s)',corrValue);
corrUnMatch = sprintf('The images are not the same (%s)',corrValue);
%Looping for the possible two outcomes
if c >=0.99 %Define a percentage for the correlation to reach
disp(' ');
disp('Images Tested:');
disp(inputImage);
disp(fullFileName);
disp (corrMatch);
disp(' ');
else
disp(' ');
disp('Images Tested:');
disp(inputImage);
disp(fullFileName);
disp(corrUnMatch);
disp(' ' );
end;
imageArray = imread(fullFileName);
imshow(imageArray);
end
You can use struct() function to create structures.
Initializing an array of struct:
imStruct = struct('fileName', '', 'image', [], 'correlation', 0);
imData = repmat(imStruct, length(jpgFiles), 1);
Setting field values:
for i = 1:length(jpgFiles)
% ...
imData(i).fileName = fullFileName;
imData(i).image = imageArray;
imData(i).correlation = corrValue;
end
Extract values of correlation field and select 5 highest correlations:
corrList = [imData.correlation];
[~, sortedInd] = sort(corrList, 'descend');
selectedData = imData(sortedInd(1:5));
I have a text file that is called paintingJobs.txt, each line is structured in this way:
Estimate Number, Estimate Date, Customer ID, Final Total, Status (E for Estimate, A for Accepted job or N for Not accepted), and Amount Paid.
Here is an extract:
E5341, 21/09/2015, C102, 440, E, 0
E5342, 21/09/2015, C103, 290, A, 290
E5343, 21/09/2015, C104, 730, N, 0
I would like the user to input any Estimate number and for that line to be outputted. How can I achieve this?
Here is what I came up with but it doesn't work as required:
def option_A():
es_num = str.upper (input ("Please enter the estimate number: "))
with open('paintingJobs.txt', 'r') as file:
line = file.readline ()
print (line, end = '')
if es_num in file:
#print whole line
else:
print("Not found")
I would like to display the information in this format
Estimate Number: the estimate number
Customer ID: the customer ID
Estimate Amount: the final total
Estimate Date: the estimate date
Status: the status
To print the line, I suggest you to simply iterate on each line of the file as follows:
def option_A():
es_num = str.upper (input ("Please enter the estimate number: "))
result = "Not found"
with open('paintingJobs.txt', 'r') as file:
for line in file:
if es_num in line:
result = line
break
print(result)
To format the display, you can split the line with comma as separator to get a list of information. Then format your display, as follows:
data = result.split(',')
print("Estimated number:{0}".format(data[0]))
print("Customer ID:{0}".format(data[2]))
...etc...
Then if you need some data which are more complex to retrieve from the text file, the powerful way is to use regex with for instance the method re.match(...).
cost = int(input("Enter the cost:\n"))
payment = int(input("Deposit a coin or note:\n"))
if payment >= cost:
change = payment - cost
print (change)
elif payment < cost:
while payment < cost:
payment = int(input("Deposit a coin or note:\n"))
change = cost - payment
print (change)
break
I basically want the value of "change".
The above was wrong because it wasn't 'storing' the value of the first payment if it was less than cost, realized my bad mistake.
cost = int(input("Enter the cost:\n"))
payment = 0
while payment < cost:
firstpayment = int(input("Deposit a coin or note:\n"))
payment = payment + firstpayment
if payment > cost:
change = payment - cost
print ("Your change is: $",change)
The loop condition says:
while payment< cost:
So, the loop automatically exists when payment becomes more than cost. So an easier approach will be,
while payment<cost:
#do something
change = payment-cost
Coz, when the loop ends, we know that payment should be >= cost...
Python 3 program allows people to choose from list of employee names.
Data held on text file look like this: ('larry', 3, 100)
(being the persons name, weeks worked and payment)
I need a way to assign each part of the text file to a new variable,
so that the user can enter a new amount of weeks and the program calculates the new payment.
Below is my code and attempt at figuring it out.
import os
choices = [f for f in os.listdir(os.curdir) if f.endswith(".txt")]
print (choices)
emp_choice = input("choose an employee:")
file = open(emp_choice + ".txt")
data = file.readlines()
name = data[0]
weeks_worked = data[1]
weekly_payment= data[2]
new_weeks = int(input ("Enter new number of weeks"))
new_payment = new_weeks * weekly_payment
print (name + "will now be paid" + str(new_payment))
currently you are assigning the first three lines form the file to name, weeks_worked and weekly_payment. but what you want (i think) is to separate a single line, formatted as ('larry', 3, 100) (does each file have only one line?).
so you probably want code like:
from re import compile
# your code to choose file
line_format = compile(r"\s*\(\s*'([^']*)'\s*,\s*(\d+)\s*,\s*(\d+)\s*\)")
file = open(emp_choice + ".txt")
line = file.readline() # read the first line only
match = line_format.match(line)
if match:
name, weeks_worked, weekly_payment = match.groups()
else:
raise Exception('Could not match %s' % line)
# your code to update information
the regular expression looks complicated, but is really quite simple:
\(...\) matches the parentheses in the line
\s* matches optional spaces (it's not clear to me if you have spaces or not
in various places between words, so this matches just in case)
\d+ matches a number (1 or more digits)
[^']* matches anything except a quote (so matches the name)
(...) (without the \ backslashes) indicates a group that you want to read
afterwards by calling .groups()
and these are built from simpler parts (like * and + and \d) which are described at http://docs.python.org/2/library/re.html
if you want to repeat this for many lines, you probably want something like:
name, weeks_worked, weekly_payment = [], [], []
for line in file.readlines():
match = line_format.match(line)
if match:
name.append(match.group(1))
weeks_worked.append(match.group(2))
weekly_payment.append(match.group(3))
else:
raise ...