I am having trouble with coordinates and flipping the cards separately. This is my first time handling with coordinates in python.
When trying to flip the cards separately, the code registers the rows of cards as lists. I did use a list of lists to display the cards.
The code is shown below.
import random
wrong = 0
used = []
cards = deck()
def mmain():
random.shuffle(cards)
selected_cards = cards[:int(result / 2)]
selected_cards = selected_cards * 2
random.shuffle(selected_cards)
i = 0
while i < len(selected_cards):
row = selected_cards[i: i + columns]
i = i + columns
grid1.append(row1)
squares = ["🎴"]
grid = []
row = []
for i in range(rows):
row.append(squares)
for e in range(columns):
grid.append(row)
while True:
for i in range(len(grid)):
print(*grid[i])
squares = str(squares)
coordinate1 = int(input("Enter the first coordinate: "))
coordinate2 = int(input("Enter the second coordinate: "))
used.append(coordinate1)
used.append(coordinate2)
if coordinate1 in range(len(grid[i])):
for k in grid[i]:
k[coordinate1] = str(selected_cards[coordinate1])
elif coordinate2 in range(len(grid[i])):
for k in grid[i]:
k[coordinate2] = str(selected_cards[coordinate2])
elif selected_cards[coordinate1] == selected_cards[coordinate1]:
grid9 = "⬛"
grid10 = "⬛"
else:
wrong = wrong + 1
if grid[i] == "⬛":
print("You win! 🥳🥳🥳🎉🎉🎉")
print("Your score is: ")
break
mmain()
I would like help on this since I am struggling with it for weeks. I appreciate the answers to solve the problem. Thank you.
Note: I already have a program that helps displays the cards.
Edit: I am sure if someone helps me with this, the question I asked could help others.
Edit2: I use Google Colab for coding in python.
Your code needs to be rewritten for clarity
Here's a template you can use, then you just need to implement each function
Test each function with test cases to ensure it works properly, then move to the next one
def main():
# create your deck
cards = initialize_cards()
# iterates until the winning condition is satisfied.
# could be a simple check that the deck is empty.
while not check_winning_condition(cards):
# ask the user for coordinates, do all the checks to ensure they are valid coordinates.
coord1, coord2 = ask_user_coordinates()
# reveals the cards to the user. Either a simple console o a sophisticated GUI
card1, card2 = reveal_cards(cards, coord1, coord2)
# checks if the cards match and removes them from the deck if needed
cards = check_cards(cards, card1, card2)
Ideally you should use classes, but for now try organizing like this.
You might need additional parameters, feel free to add the ones you need and avoid global variables.
Each function does one thing, if it does two things make two functions.
You see how simple the main function is?
Just make now each function do what is designed to do and test test test.
Related
I am currently making TicTacToe for a project using the turtle module. I made a list with the coordinates on where the turtle should go based on the input given by the user. After that, I made an if statement on if certain spots have been selected by the user, then the user would win. While making the if statement, I was using indexes to try to see if the User's inputs matched the actual coordinates. While checking in the if statement to see if specific cords match. I keep getting errors like:
TypeError: list indices must be integers or slices, not tuple
I was wondering if I wrote it incorrectly. I also know that I poorly explained it, if there are some questions, please ask. I am also very new to coding and python. I have also wrote where the error would occur.
Here is the following code:
#Code for creating turtle and image as well
import turtle as trtl
TTT = trtl
wn = trtl.Screen()
wn.addshape('O2.gif')
wn.addshape('X3.gif')
TTT.pensize(5)
TTT.speed(0)
#VARIABLES
lines = 0
x = 50
y = -50
Available_Cords = [(-100,100),(0,100),(100,100),(-100,0),(0,0),(100,0),(-100,-100),(0,-100),(100,-100)]
Taken_Cords = [(10,10)]
X_Used_Cords = [(0,0),(0,0),(0,0),(0,0),(0,0),(0,0),(0,0),(0,0),(0,0)]
Y_Used_Cords = [(0,0),(0,0),(0,0),(0,0),(0,0),(0,0),(0,0),(0,0),(0,0)]
Current_Turn = 2
#Code For creating background
while lines < 2:
TTT.penup()
TTT.goto(x,-150)
TTT.pendown()
TTT.goto(x,150)
TTT.penup()
TTT.goto(-150, y)
TTT.pendown()
TTT.goto(150, y)
x = x + -100
y = y + 100
lines = lines + 1
TTT.penup()
while True:
#code for X turn
while (Current_Turn % 2 == 0):
User_Input = int(input("X, Please enter where you like to go"))
Current_Cord = Available_Cords[User_Input - 1]
#Checking if the spot chosen has been taken, if yes then the if code will run
if Current_Cord in Taken_Cords:
print("This Spot is not Available, Try another one")
#If the spot is available, then the Else code will run which will place the image in the spot chosen
else:
TTT.shape('X3.gif')
TTT.goto(Available_Cords[User_Input - 1])
TTT.stamp()
Taken_Cords.append(Available_Cords[User_Input - 1])
#Code for Adding to list to detect if the player has won
X_Used_Cords.insert(User_Input-1 ,Available_Cords[User_Input-1])
print(X_Used_Cords)
del X_Used_Cords[User_Input]
Current_Turn = Current_Turn + 1
#LOTS OF IF STATEMENTS TO CHECK IF X WON
if X_Used_Cords[0:3] == Available_Cords[0:3]:
print("Congratulations, you won :)")
wn.mainloop()
if X_Used_Cords[3:6] == Available_Cords[3:6]:
print("Congratulations, you won :)")
wn.mainloop()
if X_Used_Cords[6:9] == Available_Cords[6:9]:
print("Congratulations, you won :)")
wn.mainloop()
#CODE WHERE THE ERROR OCCURS
if X_Used_Cords[0,3,6] == Available_Cords[0,3,6]:
print("Congratulations, you won :)")
wn.mainloop()
#Code For Y Turn
while (Current_Turn % 2 != 0):
User_Input = int(input("Y, Please enter where you like to go"))
Current_Cord = Available_Cords[User_Input - 1]
if Current_Cord in Taken_Cords:
print("This Spot is not Available, Try another one")
else:
TTT.shape('O2.gif')
TTT.goto(Available_Cords[User_Input - 1])
TTT.stamp()
Taken_Cords.append(Available_Cords[User_Input - 1])
Current_Turn = Current_Turn + 1
#Code for Adding to list to detect if the player has won
Y_Used_Cords.insert(User_Input-1 ,Available_Cords[User_Input-1])
print(Y_Used_Cords)
del X_Used_Cords[User_Input]
wn = trtl.Screen()
wn.mainloop()
The error is on line 83: X_Used_Cords[0,3,6] == Available_Cords[0,3,6] (there might be other errors).
TypeError: list indices must be integers or slices, not tuple
This syntax is invalid as you cannot slice a list with a tuple (0,3,6).
Instead either get the coordinates separately:
(X_Used_Cords[0] == Available_Cords[0]) and (X_Used_Cords[3] == Available_Cords[3]) and (X_Used_Cords[6] == Available_Cords[6])
or using all:
all(X_Used_Cords[i] == Available_Cords[i] for i in (0,3,6))
or use advanced slicing:
X_Used_Cords[0:7:3] == Available_Cords[0:7:3]
although this case works only as the indices are evenly spaced.
Hi I'm extremely new to python and was just wondering if anyone could help me/point me in the right direction, to improve my code.
import random
goal_keeper = ["Neuer","Allison", "De Gea"]
defender = ["Varane", "Ramos", "Thiago Silva","Chiellini", "Shaw", "Alaba"]
midfielder = ["De Bruyne", "Frenandes", "Modric", "Thiago","Sane", "Rashford"]
attacker = ["Lewandowski","Messi","Ronaldo","Mbappe","Neymar","Kane"]
i = int(input("How many players do you want?: "))
n_plyr = 0
squad = []
while n_plyr < i:
position_input = input("Select the players position: ")
n = int(input("How many players in that position?: "))
n_plyr = n_plyr + n
print(i-n_plyr, "left to pick for your squad")
if position_input == "goal keeper":
gk_players = random.choices(goal_keeper, k=n)
squad.append(gk_players)
if position_input == "defender":
def_players = random.choices(defender, k=n)
squad.append(def_players)
if position_input == "midfielder":
mid_players = random.choices(midfielder, k=n)
squad.append(mid_players)
if position_input == "attacker":
atk_players = random.choices(attacker, k=n)
squad.append(atk_players)
if n_plyr > i:
n_plyr = n_plyr - n
print("Squad is too big only", i-n_plyr, "left to pick")
print(routine)
The code does work im not sure how to adapt it to adding more players as expanding the list doesn't seem the right thing to do especially if I wanna add hundreds of each position. what is the best way at storing a lot more elements and then still being able to select a random number of them like i tried to above?. Also any other suggestions will be appreciated, just trying to learn and improve :)
In the end, if you have a list with hundreds of players you will need to define them somewhere. To keep the code clean I would create a file for each position and then have one player name per line. Then you can do the following:
with open('defender.txt','r') as f:
defender = f.readlines()
Like this you can have a file with hundreds of players without messing up your code.
Right now, I'm working on a 21 card trick and I've run into this error that I can't seem to crack.
def combine_columns_basedoncard(split_card_deck,TotalCardDeck):
split_card_deck = deal_deck_columns(TotalCardDeck)
for i in range(3):
card_deck = []
card_deck2 = []
card_deck3 = []
for i in range(0, 21, 3):
card_deck.append(subdeck[0 + i])
card_deck2.append(subdeck[1 + i])
card_deck3.append(subdeck[2 + i])
DealedCards = card_deck, card_deck2, card_deck3
Choice()
if (Choice == 1):
subdeck.extend(card_deck2)
subdeck.extend(card_deck)
subdeck.extend(card_deck3)
elif (Choice == 2):
subdeck.extend(card_deck)
subdeck.extend(card_deck2)
subdeck.extend(card_deck3)
else:
subdeck.extend(card_deck)
subdeck.extend(card_deck3)
subdeck.extend(card_deck2)
print(DealedCards)
Here is a function that shuffles a deck and then the user can choose which pile/subdeck their card is in, however, this code will only shuffle once and then never again and print the same list and I can't really see why this happens, or how I would go about shuffling the deck again to complete the 21 card trick. If anyone could give some suggestions that would be very much appreciated!
edit:
def Choice():
VaildChoice = False
ColumnChoice = ""
while(not VaildChoice):
ColumnChoice = input("Which column is your card in? 1, 2 or 3 ")
if("1" in ColumnChoice or "2" in ColumnChoice or "3" in ColumnChoice):
VaildChoice = True
else:
print("Invaild choice")
return ColumnChoice
Added the choice() to give a better idea of the code!
The reason is because you are extending the subdeck. When you extend the subdeck the new elements get inserted at the end. In the next iteration your subdeck length has extended but the first set of cards are still the same and they were never replaced.
To fix this initialize subdeck to empty list after Choice()
Also your outer loop iterator and inner loop iterator are both named i. Check that usage.
In my code I am trying to generate coordinates for battleship without having any repeat coordinates. I only manage far more coordinates than I asked for or none at all. What am I doing wrong in my loop/how can I fix this?
from random import randint
board = [] #Create an empty array to act as the game board.
ships = [] #Create an empty array to hold the locations of the random ships.
board_size = int(input("Enter your desired board size: ")) #Ask the user for their preferred board size.
ship_number = int(input("Enter the number of ships you want to find: ")) #Ask the user for their preferred ship number.
ships_found = 0 #Set the counter of the number of user-found ships to start at 0.
def generate_board(board_size): #Define a function to generate the initial board.
for each_item in range(board_size): #For each item in the range of the board's size,
board.append(["O"] * board_size) #Append an O to the board as many time as the user's board size says.
generate_board(board_size)
def print_board(board): #Define a function to print the current board.
for row in board: #For each row in the board,
print(" ".join(row)) #Print each chacter, separated by a space.
def generate_ships(ship_number,board):
for each_ship in range(ship_number):
new_ship = [randint(0, len(board) - 1),randint(0, len(board) - 1)]
for each_item in ships:
if each_item == new_ship:
ships.pop()
ships.append(new_ship)
else:
ships.append(new_ship)
generate_ships(ship_number,board)
While using set() to remove duplicates would technically answer the question in your title, I'd recommend rethinking your approach (and rewriting generate_ships, the logic for which looks like it might not be doing what you want it to).
Rather than randomly generating a coordinate, you could select a random element from the set of available coordinates (your board coordinates after removing the coordinates where there are already ships). This way you only ever select the number of ships you ask for and you don't have to worry about checking for duplicates.
I'm very new to Python and I hope for some help or guides by asking here.
Here's the problem:
Write a program that estimates the average number of drawings it takes before the user’s numbers are picked in a lottery that consists of correctly picking six different numbers that are between 1 and 10. To do this, run a loop 1000 times that randomly generates a set of user numbers and simulates drawings until the user’s numbers are drawn. Find the average number of drawings needed over the 1000 times the loop runs.
I tried to create something (below), but I just can't think of how to get those average number. Also it seems the loop is not good. Any help or solution? thank you in advance.
from random import randint
from random import choice #???
userlist = []
for y in range(6):
user = input("Enter your entry no.{} lotto number: ".format(y+1))
userlist.append(user)
x = 0
randomlotterylist = []
while not x>1000:
lottery = []
for i in range (6):
lot.append(randint(1,10))
randomlotterylist.append(lottery)
x = x + 1
#Next.. ????
First, you want to know your theoretical average number of drawings, that's (1/10)^6 assuming no repetition allowed. Therefore on average every 1,000,000 tries you'd hit the correct number. That is only if the order matters but I assume in your case the order does not matter, so def your average is less than that...
from random import randint
def number_of_tries_before_hitting_jackpot(user_number):
n_tries = 0
while True:
random_number = set([randint(1,10) for i in range(1,7)])
if user_number == random_number:
return n_tries
else:
n_tries+=1
def ask_user_his_number():
userlist = []
for y in range(6):
user = input("Enter your entry no.{} lotto number: ".format(y+1))
userlist.append(user)
return set(userlist)
n_tries_list = []
for x in range(1,1001):
user_number = ask_user_his_number()
print user_number
tmp = number_of_tries_before_hitting_jackpot(user_number)
print tmp
n_tries_list.append(tmp)
avg_number_drawings = reduce(lambda x, y: x + y, n_tries_list) / len(n_tries_list)
print avg_number_drawings
This code is not what I'd do in the sense that the user needs to input its 6 numbers 1,000 times (v annoying for the user). You could change the ask_user_his_number function to a function that just randomly selects a set of 6 numbers.
by using random module, for loop, list in short without defining fuction.
from random import *
user_num=[]
count=0
for i in range(6):
random_num=randint(1,10)
user_num+=[random_num]
user_num.sort()
for j in range(1000):
picked=[]
for k in range(6):
pick_num=randint(1,10)
picked+=[pick_num]
picked.sort()
if picked==user_num:
count+=1
print("the avg darwing is: ",count, count/1000)