import pygame
import random
pygame.init()
# create screen
screen = pygame.display.set_mode((1000, 600))
# Title + Logo
pygame.display.set_caption("Space Invader")
icon = pygame.image.load("chicken.png")
pygame.display.set_icon(icon)
# Player icon
player_icon = pygame.image.load("spaceship.png")
playerX = 400
playerY = 500
player_changeX = 0
player_changeY = 0
# enemy Player
enemy_icon = pygame.image.load("space-invaders.png")
enemyX = random.randint(0, 936)
enemyY = random.randint(-100, -50)
enemy_changeX = random.randint (0.1, 0.5)
enemy_changeY = random.randint (0.1, 0.5)
if enemyY >= 500:
print("Game over")
exit()
def player(x, y):
screen.blit(player_icon, (x, y))
def enemy(x, y):
screen.blit(enemy_icon, (x, y))
# game loop
running = True
while running:
# backround colour RGB
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# If key pressed check whether its right or left
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player_changeX = -1
if event.key == pygame.K_RIGHT:
player_changeX = 1
if event.key == pygame.K_UP:
player_changeY = -1
if event.key == pygame.K_DOWN:
player_changeY = 1
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
player_changeX = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
player_changeY = 0
# If player reaches boarder
if playerX >= 936:
playerX = 20
if playerX <= 0:
playerX = 936
if playerY <= 0:
playerY = 0
if playerY >= 550:
playerY = 550
# enemy control
if enemyX >= 936:
enemyX = 20
if enemyX <= 0:
enemyX = 936
if enemyY <= 0:
enemyY = 0
if enemyY >= 550:
enemyY = random.randint(-100, -50)
# Player change in coordinates
playerX += player_changeX
playerY += player_changeY
#enemy change in coordinates
enemyX += enemy_changeX
enemyY += enemy_changeY
#Results
player(playerX, playerY)
enemy(enemyX, enemyY)
pygame.display.update()
我刚开始接触编程,我正在创建一个小游戏,还没有完成,但我遇到一个问题,我想用浮点数代替整数,但不让我用。它还没有完成,但我遇到了一个问题,我想用浮点数代替整数,但它不让我这样做。你能改变这个问题吗,如果可以,怎么改变。我想使用的浮点数在 enemy_changeX 和 Y 中,它给我的错误是 。
第212行,在randrange中, raise ValueError("non-integer arg 1 for randrange()")ValueError: non-integer arg 1 for randrange()
即使我没有线212。
希望这个问题足够准确。
首先,你要求的是一个介于两者之间的整数。0.1
和 0.5
由于明显的原因,这是不可能的。
为了获得 float
你可以用 random.uniform(0.1, 0.5)
.
虽然我在这里必须指出,像素不能是浮动值,因为没有半个像素。因此,你要考虑是否真的需要一个浮动值的像素变化值。