Mafia game helper is very simple. It allows me to input the number of roles(mafia, detective, innocents etc.) first. Then each player will input their name and the computer will randomly choose a role for him/her. And the first player pass the computer to the next player and so on. At the end, computer will generate a list.
Something like:
Tom : Mafia
John : detective
Here is my code:
import random
role=[]
k = input("Number of mafia: ")
p = input("Number of detective: ")
n = input("Number of innocent: ")
---magic---
random.shuffle(role)
player = []
i=0
while True:
name = raw_input()
player.append(name)
print role[i]
i += 1
I have two problems in programming this.
How can I make a list called 'role' with k 'mafia' , and p 'detective'? For example: if k = 3, p = 1, n = 1, then the list 'role' will be ['mafia', 'mafia', 'mafia', 'detective', 'innocent']. I know that I can do it with for loop but is there any easy way (a.k.a magic) to do this?
There is a very serious bug as now the second player can see what role is assigned to the first player. How can I solve this and make no player could see this? But I have to keep the results since I have to make a list at the end as I mentioned.
My friends love to play this game so much so I want to surprise them by this program!
Thank you for everyone read this. Have a good day =]
Regarding your list generation problem
>>> k = 3
>>> p = 1
>>> n = 2
>>> roles = ['mafia']*k + ['detective']*p + ['innocent']*n
>>> roles
['mafia', 'mafia', 'mafia', 'detective', 'innocent', 'innocent']
One method to randomly assign roles
from random import shuffle
shuffle(roles)
names = ['bob', 'steve', 'tom', 'jon', 'alex', 'mike']
players = dict(zip(names,roles))
>>> players
{'mike': 'innocent',
'alex': 'mafia',
'steve': 'mafia',
'tom': 'mafia',
'bob': 'detective',
'jon': 'innocent'}
You could clear the output after assigning each person? this should now clear
import random
import os
k = input("Number of mafia: ")
p = input("Number of detective: ")
n = input("Number of innocent: ")
roles = ['mafia']*k + p*['detective'] + n * ['innocent']
random.shuffle(roles)
while roles:
print 'name:',
name = raw_input()
print 'you are a ' + roles.pop(0)
print 'clear?'
clear = raw_input()
os.system('cls' if os.name == 'nt' else 'clear')
or alternatively you could write the roles out to individual files which might work better
import random
import os
k = input("Number of mafia: ")
p = input("Number of detective: ")
n = input("Number of innocent: ")
roles = ['mafia']*k + p*['detective'] + n * ['innocent']
random.shuffle(roles)
people = []
path = ''
while roles:
print 'name:',
name = raw_input()
while name in people:
print 'name already_taken please take new name'
name = raw_input()
people.append(name)
person_file = open(os.path.join(path,'%s.txt') % (name,),'w')
person_file.write('you are a %s' % (roles.pop(0),))
person_file.close()
Related
The code is supposed to display a animated image walking in front of a background. I received this code from my professor and I'm not sure what the issue is.
import sys, os, math
sys.path.append("./")
from livewires import games
import spriteUtils
from spriteUtils import *
filename = sys.argv[1]
x = int(sys.argv[2])
y = int(sys.argv[3])
##print(filename, "\t", x, "\t", y)
games.init(screen_width = 1152, screen_height = 864, fps = 50)
nebula_image = games.load_image(os.path.join('.', "race_track.jpg"), transparent = 0)
games.screen.background = nebula_image
anim_list = load_2d_sheets(x, y, filename)
anim = games.Animation(images = anim_list,
x = games.screen.width/2,
y = 2*games.screen.height/4,
n_repeats = 15,
repeat_interval = 10)
games.screen.add(anim)
games.screen.mainloop()
I'd first print sys.argv so that you can see what it represents. For example:
$ ./myscript.py
>>> sys.argv
['/myscript.py']
>>> sys.argv[1]
IndexError
You probably want to pass additional command line arguments to your function like:
$ ./myscript.py firstvar secondvar
sys.argv[1] is the first argument that you pass to your script, so you need to run your script like this:
python my_script.py arg1
sys.argv[0] is the name of your script itself, in this example my_script.py
Looks like this script requires 3 arguments, and you aren't giving it any. The syntax for calling it on the command line is python script_name.py <file_name> <x> <y> where script_name.py is the name of the actual program, <file_name> is a string, and <x> and <y> are integers.
I am working on OCR based Android app, getting this text as string from the attached image dynamically (getting the text in Horizontal Direction from the image)
Text from Image:
"Part Name Part Cost Engine Oil and Oil Filter Replacement Rs 10K Alf Filter Rs 4500 Cabin AC Micro Filter Rs 4000 Pollen Filter Rs 1200 - 1500 AC Disinfectant Rs 3000 Fuel Filter Rs 6000 - 8000 Spark Plug Set Replacement (Applicable in TFSI / Petrol Car Range) Rs 10K Body Wash, Basic Clean 8. Engine Degrease Rs 3000 Body Wax Polish Detailed Rs 7000 - 8000 Car interior Dry Clean with Genn Clean Rs 8000 - 10000 Wheel Alignment \u0026 Balancing Rs 6000 - 7000 Brake Pads Replacernent (Pair) Rs 30K - 32K Brake Disc Replacernent (Pair) Rs 30K - 35K ..........".
I need to separate the Part Name and Part Cost(just 2 columns i.e Part Name, Part Cost) (ignore all extra text from the column heading). Separate the values from String and should store it in SQLIte Database Android. I am stuck how to get the values and separate them.
The text returned from the OCR isn't ideal. The first thing you should do is check if whatever OCR solution can be configured to provide a better output. Ideally, you want the lines to be separated by newline characters and the space between the columns to be interpreted as something more useful, such as a tab character.
If you have no way of changing the text you get, you'll have to find some way of parsing it. You may want to look into using a parser, such as ANTLR to make this easier.
The following observations may help you to come up with a parsing strategy:
Column 2 items all start with "Rs" or "Upto Rs".
Column 2 items end with:
A number (where a number is allowed to be a string of digits [0-9.], optionally followed by a "K"
"Lakh"
Column 1 items don't begin with a number or "Lakh"
So a basic algorithm could be:
List<String> column1 = new ArrayList<String>();
List<String> column2 = new ArrayList<String>();
String[] tokens = ocrString.split(" ");
List<String> column = column1;
String item = "";
for (int i = 0; i < tokens.length; i++) {
String token = tokens[i];
String nextToken = i == tokens.length - 1 ? "" : tokens[i+1];
if (column == column1) {
if (token == "Rs" || (token == "Upto" && nextToken == "Rs")) {
column = column2;
column.add(item); item = "";
i--; continue;
}
item += " " + token;
} else {
item += " " + token;
if (/*token is number or "Lakh" and nextToken is not*/) {
column.add(item); item = "";
column = column1;
}
}
}
I have a textField value as 12345678955. I want to format this value as 1,234,567.8955
Want to seperate the value with comma.
I have tired with some codes. But it doesn't work.
Well, you would want to get your 4 decimal places you would need to divide your number by 10000:
var newNumber = parseInt($.yourTextField.value);
newNumber = Math.round(Number(newNumber)) / 10000;
console.log(newNumber); // 1234567.8955
Next you want to add your commmas:
var parts = newNumber.toString().split(".");
var num = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");
console.log(num); // 1,234,567.8955
Thats the functionality, how you tie that to your textField and by which event listener, is yours to work out.
(answer adapted from https://stackoverflow.com/a/25127753/829989 which you could have easily found on your own)
This function reads a file line by line and sets global variables to the values read accordingly. However, the problem is that this code works on the simulator 100% fine however once compiled and run on the android device it stops working. Through the use of displaying text I have located the error to be on the line of code: "mapObject[i].x = sum". The attribute .x is of type real and I've already confirmed that sum, numerator and denominator are all numerical data types. The app crashes on the first run through of the loop containing "mapObject[i].x = sum" so i = 1. 1 is within range of the array. Any help is appreciated, I just can't get my head around this. Here is the function code:
-- Read map from file
local function loadmap(mapnum)
local tempstring
local numerator
local denominator
local sum
local i
local path = system.pathForFile( "maps/map" .. mapnum .. ".txt", system.ResourceDirectory)
--Open the file
local fh = io.open( path, "r" )
if fh then
-- read the lines of data systematically.
mapName = fh:read( "*l" )
mapNPCS = fh:read( "*l" )
mapSpawnTimer = tonumber(fh:read( "*l" ))
mapSpawnMax = tonumber(fh:read( "*l" ))
mapSpawnMaxLocations = tonumber(fh:read( "*l" ))
mapObjectMax = tonumber(fh:read( "*l" ))
for i = 1, mapObjectMax do
tempstring = fh:read( "*l" )
mapObject[i] = display.newImage("graphics/" .. tempstring .. ".png")
-- Fractional mapping for all screen sizes
denominator = tonumber(fh:read( "*l" ))
numerator = tonumber(fh:read( "*l" ))
sum = (display.contentWidth / denominator) * numerator
mapObject[i].x = sum
denominator = tonumber(fh:read( "*l" ))
numerator = tonumber(fh:read( "*l" ))
sum = (display.contentHeight / denominator) * numerator
mapObject[i].y = sum
mapObject[i].myName = "object"
physics.addBody(mapObject[i], "kinematic", {density = 10.0, friction = 0.0})
end
for i = 1, mapSpawnMaxLocations do
mapSpawnX[i] = tonumber(fh:read( "*l" ))
mapSpawnY[i] = tonumber(fh:read( "*l" ))
end
io.close( fh )
end
end
here is the global variables that come with the code:
-- Map Data Variables
local mapName
local mapNPCS
local mapSpawnTimer
local mapSpawnMax
local mapSpawnMaxLocations
local mapObjectMax
local mapObject = {}
local mapSpawnX = {}
local mapSpawnY = {}
-- Map Npc Spawning
local mapNPC = {}
local maxMapNPCS = 30
local npcsSpawned
local spawnTimer = 0
Some things to try on physical device:
If you use sum = display.contentWidth does it work?
How about sum = 100?
Could it be that the denominator is 0? (although that shouldn't cause a crash, just an error)
Try replacing mapObject[i].x = sum by mapObject[i].x = 100, does it still crash?
could it be that mapObject[i] is not a valid display object, say if the path in mapObject[i] = display.newImage("graphics/" .. tempstring .. ".png") is not valid or if tempstring is empty? (although you'd think display.newImage('graphics/.png') should not cause any trouble)
I'm going to guess that:
mapObject[i] = display.newImage("graphics/" .. tempstring .. ".png")
is producing a file name that's invalid on the device. Device's are case sensitive, where as the simulator is not.
I get error message when i try to insert a table into a group
My table code is containing images
Here is the code i am using for the table
local myJoints = {}
for i = 1,5 do
local link = {}
for j = 1,17 do
link[j] = display.newImage( "link.png" )
link[j].x = 121 + (i*34)
link[j].y = 55 + (j*17)
physics.addBody( link[j], { density=2.0, friction=0, bounce=0 } )
-- Create joints between links
if (j > 1) then
prevLink = link[j-1] -- each link is joined with the one above it
else
prevLink = wall -- top link is joined to overhanging beam
end
myJoints[#myJoints + 1] = physics.newJoint( "pivot", prevLink, link[j], 121 + (i*34), 46 + (j*17) )
end
end
and here is the code for group
GUI:insert(myJoints);
i have my background image in the GUI group and it is covering the table.
I don't know if it is actually possible to insert table into a group
Any help please
Thanks in Advance!
You can't insert a table into a group using the "insert" method because that method is looking for a display object. Try calling GUI.myJoints = myJoints. Also keep in mind that your table just references your display objects, which is different from having them in a group.