简体   繁体   中英

How do I get the correct outputs for this chess board?

I am trying to make a program of a chess board, When a user inputs an x and y value it will either output "black" or "white".

x = int(input("Please enter your (x) first number 1-8::"))
y = int(input("Please enter your (y) second number 1-8::"))

column = x % 2
row = y % 2


if column %2 == 0 and row %2 == 1:
  
    print("")
    print("white")


elif row %2 ==0 and column %2 == 1:
    print("")
    print("black")

Whenever i input 1 for "x" and 2 for "y" it outputs "black", great this is the correct output. But whenever i input some other numbers such as 2 and 2, it gives me a blank output. Whenever i input 1 and 4, it outputs "black" which the correct output should have been "white. How do i make it so that whenever user inputs two numbers ranging from 1 to 8, it outputs the correct colour tile? I am not trying to make the code more advanced but would appreciate some help!

This is the chess board i am basing the colours on.( Do not mind the text on the picture)

在此处输入图像描述

Instead of looking at x and y separately, just check the sum. If the sum is even, it's black, if the sum is odd, it is white.

I added a lookup of the name in a python dict, but you can just do it with if conditions if you prefer.

x = int(input("Please enter your (x) first number 1-8::"))
y = int(input("Please enter your (y) second number 1-8::"))

color_picker = {0: "Black", 1: "White"}

if not 0<x<9 or not 0<y<9:
    print("Input valid number!!")
else:
    color
    print(color_picker[(x+y)%2])

Let me know if it helps.

if column %2 == 0 and row %2 == 1:
    ...

elif row %2 ==0 and column %2 == 1:
    ...

This covers the case where column is even and row is odd, and the case where row is even and column is odd.

But what about the cases where they are both even, or both odd?

x = int(input("Please enter your (x) first number 1-8::"))
y = int(input("Please enter your (y) second number 1-8::"))

column = x
row = y


if (column + row) %2 == 0:

    print("")
    print("black")


elif (column + row) %2 == 1:
    print("")
    print("white")

else:
    print("Input valid number!!")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM