import curses
import pygame as pg
def main(stdscr):
stdscr.nodelay(1) # Makes the `getch` method non-blocking.
# Use `addstr` instead of `print`.
stdscr.addstr('Press "Esc" to exit...\n')
command = '' # Add the entered characters to this string.
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
rect = pg.Rect(300, 100, 30, 50)
while True:
for event in pg.event.get():
if event.type == pg.QUIT:
return
inpt = stdscr.getch() # Here we get the pressed key.
if inpt == 27: # Esc
return
elif inpt in (ord('\n'), ord('\r')): # Enter pressed.
# Check which command was entered and move the rect.
if command == 'move right':
rect.x += 20
elif command == 'move left':
rect.x -= 20
command = '' # Reset the command string.
stdscr.addstr(2, 0, '{}\n'.format(command)) # Write in the second line.
elif inpt == 8: # Backspace
command = command[:-1]
stdscr.addstr(2, 0, '{}\n'.format(command))
elif inpt not in (-1, 0): # ValueErrors if inpt is -1 or 0.
command += chr(inpt) # Concatenate the strings.
stdscr.addstr(2, 0, '{}\n'.format(command))
screen.fill((30, 30, 30))
pg.draw.rect(screen, (0, 120, 250), rect)
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
pg.init()
# Use the curses.wrapper to start the program. It handles
# exceptions and resets the terminal after the game ends.
curses.wrapper(main)
pg.quit()
1和100都是int类型,b是char类型,所以不应该导致编译错误?我不明白为什么它会返回"版本1"。
有人可以向我解释原因吗?谢谢
答案 0 :(得分:1)
在运行时,您的编译器会将int 100
转换为double
类型,因为您没有其他选择(即另一个重载方法完全接受int
,int
和{ {1}})。
换句话说,您的编译器不是抛出char
,而是将占用较小大小的RuntimeException
转换为占用更多大小的类型(在您的情况下为int
)。这是自动执行而不会丢失信息。
这称为Widening Primitive Conversion或自动转化或隐式转化。