How can I daw a playing board with the help of python - python-3.x

Create a function that takes in two parameters: rows, and columns, both of which are integers. The function should then proceed to draw a playing board (as in the examples from the lectures) the same number of rows and columns as specified. After drawing the board, your function should return True.

def tictactoeboard(rowsorcolumns):
rowsorcolumns = int(rowsorcolumns)
# Number of rows and columns have been equated to keep a square tic-tact-toe board
if (rowsorcolumns) < 3 or (rowsorcolumns) > 21:
print("The number of rows or columns must be at least 3 OR at most 20")
return False
# For my screen, a comfortable size is that with 13 rows and columns
else:
for rows in range(rowsorcolumns):
if rows != rowsorcolumns-1:
for columns in range(rowsorcolumns):
if columns == 0:
print("__", end="")
elif columns != 0 and columns != rowsorcolumns-1:
print("|__", end="")
else:
print("|__")
else:
for columns in range(rowsorcolumns):
if columns == 0:
print(" ", end="")
elif columns != 0 and columns != rowsorcolumns-1:
print("| ", end="")
else:
print("| ")
return True
tictactoeboard(input("Enter the number of rows OR columns that you want for the board = "))

def Game_Board(rows, columns):
max_columns = 100
max_rows = 50
rows = int(rows)
columns = int(columns)
if columns <= max_columns and rows <= max_rows:
for r in range((rows-1)*2+1):
if r%2 == 1:
print("-"*(2*columns-1))
else:
print(" |"*(columns-1))
else:
print("rows and columns are above table values")
return
Print_Board = Game_Board(50, 100)
print(Print_Board)

Creating a playing board
def playingBoard(row, col):
for r in range(row):
if r % 2 == 0:
for c in range(1, col):
if c % 2 == 1:
if c != 5:
print(" ", end=" ")
else:
print(" ")
else:
print("|", end=" ")
else:
print("--------")
row = 5enter code here
col = 6
print(playingBoard(row, col))

Related

for loops with lots of if conditions while creating a new column

I am trying to convert 1 column (kinda 2) of categories (strings) into a set of numbers 1 for star, 2 qso, 3 for galaxies that are not agn (second column defines that) and then 4 for galaxies that are AGN.all saved on a new column of the dataframe.
for n ,i, l in zip(data_clean['class'], data_clean['subClass'], data_clean['nClass'] ):
if n == 'STAR':
l = 1
elif n == 'QSO':
l=2
elif n == 'GALAXY' and i != 'AGN':
l=3
elif n == 'GALAXY' and i == 'AGN':
l=4
where class is the major category, subclass where I get the AGN classification and the nclass is the new column where I put the new integer classification. But I get all zeros. What am I doing wrong?
Does this do what you want?
def type_to_value(n, i):
if n == 'STAR':
return 1
elif n == 'QSO':
return 2
elif n == 'GALAXY' and i != 'AGN':
return 3
elif n == 'GALAXY' and i == 'AGN':
return 4
data_clean['nClass'] = [type_to_value(n, i) for n, i in zip(data_clean['class'], data_clean['subClass'])]
There is no indentations on your for loop?
Try:
for n ,i, l in zip(data_clean['class'], data_clean['subClass'], data_clean['nClass'] ):
if n == 'STAR':
l = 1
elif n == 'QSO':
l=2
elif n == 'GALAXY' and i != 'AGN':
l=3
elif n == 'GALAXY' and i == 'AGN':
l=4
I can't use tab here, so just try to do equal in your code. Don't copy and paste.

Python multiply game. My script needs to have a arbitrarily number of players that each have to take turn in answering a multiplication question

Basically i need to make a game im python that can have a arbitrarily number of people that alternatly answers a multiplication question. But my issue is that i dont know how to keep it running until i hit 30 points. Ive tried to use dict's where the key is the player name and the value is the score. But it stops after the script only has ran once. I tried with a while loop but it went on forever. please help!
import random as r
n = int(input("Insert number of players: "))
d = {}
for i in range(n):
keys = input("Insert player name: ")
#to set the score to 0
values = 0
d[keys] = values
#to display player names
print("Player names are:")
for key in d:
print(key)
for value in d.values():
if value < 30:
random1 = r.randint(0,9)
random2 = r.randint(0,9)
print(f"The two numbers you should multiplie is {random1} and {random2}")
correct = random1*random2
user_inp = input("Insert answer: ")
user_inp = int(user_inp)
if user_inp == correct:
print("Correct!")
d[keys] += 1
else:
print("Wrong!")
d[keys] -= 2
else:
break
I think this will work
winner = False
while not winner :
for value in d.values():
if value < 30:
random1 = r.randint(0,9)
random2 = r.randint(0,9)
print(f"The two numbers you should multiplie is {random1} and {random2}")
correct = random1*random2
user_inp = input("Insert answer: ")
user_inp = int(user_inp)
if user_inp == correct:
print("Correct!")
d[keys] += 1
else:
print("Wrong!")
d[keys] -= 2
else:
winner = True
break

Issues with 'movement' across multi-dimensional array, text-based game

I'm currently messing around with the code right now to solve some issues in movement. Ideally, i want to be able to move the character to any spot in the array(worldMap) containing ' ', and marking the player's position with 'P'.
I'm lost to what the issue I am running into is, and some of the issues I am running into are as follows...
- when I move E it always goes to worldMap[3][3]
- N only moves up from worldMap[3][x] to worldMap [2][x]
- S doesn't work
Below is my current code...
import math
import random
import sys
import os
import time
gameplay= True
#world map lay out, X--> wall, player can't go that way. ' ', possible area for player to move, 'P', player indicator.
worldMap = [['X','X','X','X','X'],
['X',' ',' ',' ','X'],
['X',' ',' ',' ','X'],
['X','P',' ',' ','X'],
['X','X','X','X','X']]
west=str("w" or "W")
east=str("e" or "E")
north=str('n' or 'N')
south=str('s' or 'S')
for row in worldMap:
for column in row:
print(column, end=' ')
print()
while gameplay == True:
x=str((input("\nWhat direction would you like to move?\n ")))
if x==west:
for row in worldMap:
for i, column in enumerate(row):
if column == 'P':
if((i>0) and (i<4) and row[i-1]) == ' ':
row[i-1] = 'P'
row[i]=' '
else:
print("\nCan't do that.\n")
for row in worldMap:
for column in row:
print(column, end=' ')
print()
elif x==east:
for row in worldMap:
for i, column in enumerate(row):
if column == 'P':
if((i>0) and (i<4) and row[i+1]) == ' ':
row[i+1] = 'P'
row[i]=' '
else:
print("\nCan't do that.\n")
for row in worldMap:
for column in row:
print(column, end=' ')
print()
elif x == north: #move north
for column in worldMap:
for i, row in enumerate(column):
if row == 'P':
if((i>0) and (i<4) and column[i-1]) == ' ':
column[i-1] = 'P'
column[i]=' '
else:
print("\nCan't do that.\n")
for row in worldMap:
for column in row:
print(column, end=' ')
print()
elif x== south: #move south
for column in worldMap:
for i, row in enumerate(column):
if column == 'P':
if((i>0) and (i<4) and column[i+1]) == ' ':
column[i+1] = 'P'
column[i]=' '
else:
print("\nCan't do that.\n")
for row in worldMap:
for column in row:
print(column, end=' ')
print()
else:
for row in worldMap:
for column in row:
print(column, end=' ')
print()
print("\nCan't do that.\n")
I have tided up your code a bit. A good clue to needing to refactor your code is if you have written the same thing alot in your code. In those cases its better to write a function and then call the function from your code. The below code is just an example to help set you on the right path.
In this example instead of scanning the whole map for the player, i just keep track of the players position and calculate the new position and if its a space then move the player. We can easily move the player by adding or subtracting 1 to the x or y co-ordinate of the player.
I also cleaned up the print map function and its now only called at the start of each loop.
from random import randint
def generate_map(size):
# world map lay out, X--> wall, player can't go that way. ' ', possible area for player to move, 'P', player indicator.
world_map = [[wall for _ in range(size)]]
for i in range(1, size - 1):
world_map.append([wall])
for j in range(1, size - 1):
#generate random walls in our map (currently set to genearete spaces 90% of the time
if randint(1,100) < 90:
world_map[i].append(space)
else:
world_map[i].append(wall)
world_map[i].append(wall)
world_map.append([wall for _ in range(size)])
return world_map
def print_map():
for row in worldMap:
print(" ".join(row))
def move_player():
x, y = player_position
if direction == "W":
y -= 1
elif direction == "E":
y += 1
elif direction == "N":
x -= 1
elif direction == "S":
x += 1
if worldMap[x][y] == space:
worldMap[player_position[0]][player_position[1]] = space
worldMap[x][y] = player
player_position[0] = x
player_position[1] = y
else:
print("Cannot more there")
#Genearte a map and position the player
wall, space, player = "X", " ", "P"
map_size = 10
worldMap = generate_map(map_size)
player_position = [1, 1]
worldMap[player_position[0]][player_position[1]] = player
#Run the game
gameplay = True
while gameplay:
print_map()
direction = input("\nWhat direction would you like to move? ").upper()
if direction:
move_player()
else:
break

python accumulating while loop keeps repeating what did i do wrong?

I can't figure out what I am doing wrong. I have tried using a break, and tried setting what the variable !=, I am doing this on cengage and it is very finnicky.
""" LeftOrRight.py - This program calculates the total number of left-handed and right-handed students in a class. Input: L for left-handed; R for right handed; X to quit. Output: Prints the number of left-handed students and the number of right-handed students."""
rightTotal = 0 # Number of right-handed students.
leftTotal = 0 # Number of left-handed students.
leftOrRight = input("Enter an L if you are left-handed,a R if you are right-handed or X to quit.")
while leftOrRight != "X":
print (leftOrRight)
if leftOrRight == "L":
leftTotal = (leftTotal + 1)
elif leftOrRight == "R":
rightTotal = (rightTotal + 1)
else:
break
print("Number of left-handed students: " + str(leftTotal))
print("Number of right-handed students: " + str(rightTotal))
your input() is outside the while loop, so leftOrRight never changes, never get to X so it will not exit the loop:
leftOrRight = None
while leftOrRight != "X":
leftOrRight = input("Enter an L if you are left-handed,a R if you are right-handed or X to quit.")
print (leftOrRight)
if leftOrRight == "L":
leftTotal = (leftTotal + 1)
elif leftOrRight == "R":
rightTotal = (rightTotal + 1)
else:
break
According to your code you are not changing the value for leftOrRight after entering the loop so the condition for your while loop is never false I would suggest the following edit:
""" LeftOrRight.py - This program calculates the total number of left-handed and right-handed students in a class. Input: L for left-handed; R for right handed; X to quit. Output: Prints the number of left-handed students and the number of right-handed students."""
rightTotal = 0 # Number of right-handed students.
leftTotal = 0 # Number of left-handed students.
leftOrRight = '' #anything random
while leftOrRight != "X":
leftOrRight = input("Enter an L if you are left-handed,a R if you are right-handed or X to quit.")
print (leftOrRight)
if leftOrRight == "L":
leftTotal = (leftTotal + 1)
elif leftOrRight == "R":
rightTotal = (rightTotal + 1)
else:
break
print("Number of left-handed students: " + str(leftTotal))
print("Number of right-handed students: " + str(rightTotal))
so that you get a prompt every time the loop is executed and you can click X to exit
Your program just got the character that had the largest id in the ascii table.
And only doing the first string as the longString = max(n) wasn't even in the while loop.
also max returns the largest value, so in this case it was just converting the text into an ascii number.
instead you should use len(string) which returns the length of the string.
Unlike max() which is used like:
11 == max(11,10,1,2) as 11 is the largest character.
n = (input("Input: ")) #get initial input
longest = 0 #define the varible which we will keep the length of the longest string in
longest_str = "" #define the varible which stores the value of the longest string.
while n: #you don't need that other stuff, while n does the same as while n != ''
n = str(input("Input: ")) #get input
length = len(n) #gets the length of the input
if length > longest: #if the length of our input is larger than the last largest string
longest = length #set the longest length to current string length
longest_str = n #set the longest string to current string
#once the user hits enter (typing "") we exit the while loop, and this code runs afterwards.
print("Longest input was", longest_str, "at", longest, "characters long")
Because there are two specific counts we are accumulating for, and the outlying char is at the end of our input, we can set our while to True to break when we hit a char other that "L" or "R".
leftOrRight = ""
# Write your loop here.
while True:
leftOrRight = input("Enter an L if you are left-handed,a R if you are right-handed or X to quit.")
if leftOrRight == "L":
leftTotal = leftTotal + 1
elif leftOrRight == "R":
rightTotal = rightTotal + 1
else:
break
# Output number of left or right-handed students.
print("Number of left-handed students: " + str(leftTotal))
print("Number of right-handed students: " + str(rightTotal))

Cannot keep certain numbers from averaging

I need help. I'm trying to run the program below. When I enter a number above 100 or below 0 I need it to disregard that input any advice?
total = 0.0
count = 0
data = int(input("Enter a number or 999 to quit: "))
while data != "":
count += 1
number = float(data)
total += number
data = int(input("Enter a number or 999 to quit: "))
try:
data = int(data)
except ValueError:
pass
average = round(total) / count
if data == 999:
break
elif data >= 100:
print("error in value")
elif data <= 0:
number = 0
print("error in value")
print("These", count, "scores average as: ", round(average, 1))
You could move the average = ... line behind the checking for invalid numbers and add continue to the checks for invalid numbers. So the last lines would end up like this:
if data == 999:
break
elif data >= 100:
print("error in value")
continue
elif data <= 0:
print("error in value")
continue
average = round(total) / count

Resources